在 Java Applet 開發中,因安全機制限制,Applet 無法直接對本地文件系統進行讀寫操作。雖然在開發環境(如 Cafe)中調試時文件操作代碼能正常運行,但一旦部署到瀏覽器中,便會拋出安全異常。那麼,當我們確實需要在 Applet 中顯示伺服器上的文本文件(如 .txt)內容時,該如何破解?
關鍵在於不將伺服器文件作為普通文件處理,而是將其作為網絡資源通過 HTTP 協議獲取。Java 提供了兩個核心類來實現此功能:java.net.URL 和 java.net.URLConnection。兩者均支持以字節流方式讀取資源,並能判斷資源類型以便後續處理。不同之處在於 URLConnection 提供更豐富的元數據,如資源長度、最後修改時間、編碼格式、Content-Type 等。
URL(String protocol, String host, int port, String file):構造完整 URL 對象URL(String protocol, String host, String file):使用預設端口構造URL(String spec):從字符串解析構造URL(URL context, String spec):基於基礎 URL 與相對路徑構造Object getContent():直接獲取資源內容對象InputStream openStream():獲取輸入流讀取數據URLConnection openConnection():建立連接對象以獲取更多控制權protected URLConnection(URL url):構造方法(通常由 URL.openConnection() 調用)Object getContent():獲取資源內容InputStream getInputStream():獲取字節輸入流static String guessContentTypeFromStream(InputStream is):根據流推測 MIME 類型假設伺服器 IP 為 202.114.1.16,文件路徑為 /file/sample.txt。以下是完整的 Applet 實現代碼:
<HTML>
<HEAD><TITLE>讀取伺服器文本文件的 Applet</TITLE></HEAD>
<BODY>
這是伺服器上 TXT 文件的內容<BR>
<Applet code="getFile.class" width=200 height=100>
</Applet>
</BODY>
</HTML>
import java.awt.*;
import java.applet.*;
import java.net.*;
import java.io.*;
public class getFile extends Applet {
String info;
public void init() {
URL url;
URLConnection urlc;
resize(200, 100);
setBackground(Color.white);
try {
url = new URL("https://202.114.1.16/file/sample.txt");
urlc = url.openConnection();
urlc.connect();
info = getInfo(urlc);
} catch (MalformedURLException mfe) {
System.out.println("URL 格式錯誤!");
} catch (IOException ioe) {
System.out.println("IO 異常!");
}
}
// 輔助方法:從連接讀取文本內容
private String getInfo(URLConnection conn) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
return sb.toString();
}
public void paint(Graphics g) {
if (info != null) {
g.drawString(info, 10, 30);
}
}
}
URLConnection 更靈活。MalformedURLException 和 IOException。InputStreamReader 的字符集(如 UTF-8),避免亂碼。掌握此技巧,即可在 Applet 安全模型下優雅地實現伺服器文件內容的動態加載與展示。