首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 網路程式設計實戰(二):文件讀取、動態更新與 URL 多種建立方式

     編輯:Java 相關知識

延續前篇內容,本文深入探討 Java Applet 與 Application 在網路資源存取上的進階應用,包含顯示遠端 HTML 文件、讀取網路檔案內容、動態輪詢更新資料,以及 URL 物件的多種建立方式。

顯示網路上的其他 HTML 文件

利用 getAppletContext().showDocument(URL) 可在新視窗或當前視窗開啟指定 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 更能讀取並處理網路檔案內容。標準流程四步驟:

  1. 建立 URL 物件
  2. 呼叫 openStream() 取得 InputStream
  3. 包裝為 DataInputStream 或 BufferedReader
  4. 逐行或逐字元讀取並處理
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) {
        // 處理每一行資料
        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 安全限制與 Application 替代方案

安全性考量下,Applet 僅能連回其所在主機(同源策略)。繞過限制的方法:

  • 將編譯後的 class 放置於同源主機
  • 本機瀏覽器以 File → Open File 開啟 HTML 不受限
  • 改寫為 Java Application 完全無此限制

Application 版本範例

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);
            }
        }
    }
}

URL 物件的四種建立方式

  1. new URL(String spec) — 完整 URL 字串
  2. new URL(String protocol, String host, String file) — 協定、主機、路徑分離
  3. new URL(String protocol, String host, int port, String file) — 含連接埠號
  4. 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");

進階網路功能:URLConnection 與 Socket

除 URL 類別外,Java 更提供:

  • URLConnection — 支援 HTTP 標頭設定、POST 請求、與 CGI 程式互動
  • Socket/ServerSocket — 底層 TCP 通訊,自訂協定、開發 Client/Server 架構

掌握這些 API,即可構建功能完整的網路應用程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved