アプレットからサーバー上のファイルを読み込む方法(Tomcat 3.2.4)
・htmlのソース
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<meta http-equiv="Pragma" content="no-cache">
<title>communication</title>
</head>
<body>
<applet code="FileRead.class" codebase="." width="400" height="400">
</body>
</html>
・アプレットのソース
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class FileRead extends Applet{
private Button button;
private TextArea textArea;
private ActionListener buttonAction = new ActionListener(){
public void actionPerformed(ActionEvent e){
button_pushed(e);
};
};
public void init(){
button = new Button("読み込み");
textArea = new TextArea(20, 50);
button.addActionListener(buttonAction);
add(button);
add(textArea);
}
private void button_pushed(ActionEvent e){
try{
URL url = getCodeBase();
String fileName = url.toString() + "test.html";
url = new URL(fileName);
URLConnection uc = url.openConnection();
int length = uc.getContentLength();
byte[] fileBuffer = new byte[length];
InputStream is = uc.getInputStream();
is.read(fileBuffer);
is.close();
for(int j = 0 ; j < length ; j++){
textArea.append(String.valueOf((char)fileBuffer[j]));
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
・実行結果