如何使用Applet读取文件?(How to read a file using Applet?)
优质
小牛编辑
128浏览
2023-12-01
问题描述 (Problem Description)
如何使用Applet读取文件?
解决方案 (Solution)
以下示例演示了如何使用URL的openStream()方法使用Applet读取文件。
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class readFileApplet extends Applet {
String fileToRead = "test1.txt";
StringBuffer strBuff;
TextArea txtArea;
Graphics g;
public void init() {
txtArea = new TextArea(100, 100);
txtArea.setEditable(false);
add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");
if (prHtml != null) fileToRead = new String(prHtml);
readFile();
}
public void readFile(){
String line;
URL url = null;
try {
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e){}
try {
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null) {
strBuff.append(line + "\n");
}
txtArea.append("File Name : " + fileToRead + "\n");
txtArea.append(strBuff.toString());
} catch(IOException e) {
e.printStackTrace();
}
}
}
结果 (Result)
上面的代码示例将在启用Java的Web浏览器中生成以下结果。
View in Browser.