利用Java提供的getAppletContext().showDocument(URL)可以顯示其他結點的HTML文檔,同前面的顯示網絡上其他結點的圖象,有兩種格式,下面各舉一例:
●程序8 格式一
import java.applet.*; import java.awt.*; import java.net.*; public class showdoc extends Applet { URL docur= null; public void paint(Graphics g) { try { docur=new URL("http://www.shu.edu.cn/~xyx/doc/manhua.html"); } catch (MalformedURLException e) { System.out.println("Can´t open the URL "); } if (docur != null) { getAppletContext().showDocument(docur,"_blank"); } } } |
●程序9 格式二
import java.applet.*; import java.awt.*; import java.net.*; public class showdoc2 extends Applet { URL docur= null; public void paint(Graphics g) { try { getAppletContext().showDocument(new URL("http://www.shu.edu.cn/ ~xyx/doc/manhua.html")); } catch (MalformedURLException e) { System.out.println("Can´t open the URL "); } } } |
六、讀取網絡上文件內容
前述的網絡功能只是顯示或播放網絡上結點的圖象、 聲音及HTML文檔,並沒有對其內容進行處理。事實上,Java還可讀取網絡上文件的內容,並對其內容進行處理。
讀取網絡上文件內容的步驟可如下:
1. 創建一個URL類型的對象
如:
String url = "ftp://202.120.127.218/incoming/test/readtxt.html"; URL fileur; try { fileur = new URL(url); } catch ( MalformedURLException e) { System.out.println("Can´t get URL: " ); } |
2. 利用URL類的openStream(),獲得對應的InputStream類的對象,如:
InputStream filecon = fileur.openStream(); |
3. 將InputStream對象轉化爲DataInputStream類的對象,如:
DataInputStream filedata = new DataInputStream(filecon); |
4. 讀取內容
如對前面的filedata,可用filedata.readLine() 一行一行讀取內容,或用filedata.readchar一個字符一個字符讀取內容。 對讀取到的內容,可由Java Applet進行各種處理, 並將處理結果用各種方式顯示出來。
下面的例子是讀取 http://www.shu.edu.cn/~xyx/doc/manhua.html文件內容的例子,爲簡潔起見,該例中只將文件的內容逐行讀出,並在文本區顯示出來。
●程序10
import java.io.*; import java.net.*; import java.awt.*; import java.applet.*; public class showfile extends Applet{ URL fileur; TextArea showarea = new TextArea("Please wait a while for get text",10,70); public void init() { String url = "http://www.shu.edu.cn/~xyx/doc/manhua.html"; try { fileur = new URL(url); } catch ( MalformedURLException e) { System.out.println("Can´t get URL: " ); } add(showarea); } public void paint(Graphics g) { InputStream filecon = null; DataInputStream filedata = null; String fileline; try { filecon = fileur.openStream(); filedata = new DataInputStream(filecon); while ((fileline = filedata.readLine()) != null) { showarea.appendText(fileline+"/n"); } } catch (IOException e) { System.out.println("Error in I/O:" + e.getMessage()); } } } |