延續前篇內容,本文深入探討 Java Applet 與 Application 在網路資源存取上的進階應用,包含顯示遠端 HTML 文件、讀取網路檔案內容、動態輪詢更新資料,以及 URL 物件的多種建立方式。
利用 getAppletContext().showDocument(URL) 可在新視窗或當前視窗開啟指定 URL。兩種常用格式:
URL docUrl = new URL("https://example.com/doc.html");
getAppletContext().showDocument(docUrl, "_blank"); // 新視窗
getAppletContext().showDocument(new URL("https://example.com/doc.html"));
此功能不受 Applet 安全沙箱限制,可從任意主機開啟文件。
除了顯示資源,Java 更能讀取並處理網路檔案內容。標準流程四步驟:
URL 物件openStream() 取得 InputStreamDataInputStream 或 BufferedReaderURL url = new URL("https://example.com/data.txt");
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = br.readLine()) != null) {
// 處理每一行資料
textArea.append(line + "\n");
}
}
結合執行緒可實現定時自動更新。以下範例每 5 秒讀取一次遠端資料:
public class DynamicDisplay extends Applet implements Runnable {
Thread pollThread;
URL dataUrl;
TextArea displayArea;
public void init() {
dataUrl = new URL("https://example.com/live-data.txt");
displayArea = new TextArea("載入中...", 10, 70);
add(displayArea);
}
public void start() {
if (pollThread == null) {
pollThread = new Thread(this);
pollThread.start();
}
}
public void stop() {
if (pollThread != null) {
pollThread.interrupt();
pollThread = null;
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(dataUrl.openStream()))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
// SwingUtilities.invokeLater 更新 UI(略)
} catch (IOException e) {
// 錯誤處理
}
try { Thread.sleep(5000); } catch (InterruptedException e) { break; }
}
}
}
此技術適用於股市行情、即時新聞等動態資料展示,配合圖形繪製更可呈現動態曲線。
安全性考量下,Applet 僅能連回其所在主機(同源策略)。繞過限制的方法:
File → Open File 開啟 HTML 不受限public class UrlReaderApp {
public static void main(String[] args) throws Exception {
URL url = new URL("https://example.com/data.txt");
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
new URL(String spec) — 完整 URL 字串new URL(String protocol, String host, String file) — 協定、主機、路徑分離new URL(String protocol, String host, int port, String file) — 含連接埠號new URL(URL base, String relative) — 基準 URL + 相對路徑// 範例
new URL("http", "example.com", "/path/file.html");
new URL("http", "example.com", 8080, "/path/file.html");
new URL(baseUrl, "subdir/file.html");
除 URL 類別外,Java 更提供:
URLConnection — 支援 HTTP 標頭設定、POST 請求、與 CGI 程式互動Socket/ServerSocket — 底層 TCP 通訊,自訂協定、開發 Client/Server 架構掌握這些 API,即可構建功能完整的網路應用程式。