實驗要求:
創建一個URL對象,然後讓URL對象返回輸入流,通過該輸入流讀取URL所包含的資源文件
--------說白了就是你項目裏有個文件,讀出來,我採用的本地服務器 運行如下
一、先搭建本地服務器
1.控制面板)程序)程序和功能)啓用或關閉 Windows 功能—Internet Information Services全選,等待修改完成
2.控制面板)所有控制面板項,管理工具)選擇Internet信息服務(IIS)管理器,網站處右鍵–添加網站
其中應用程序選DefaultAppPool,可以自己分配ip和端口,默認也行,物理路徑添加你的項目,最後點確定
然後就能看見已經添加了 右邊選擇瀏覽
首次可能會出現以下報錯:
那麼我們就按照提示操作操作一遍,在網站選中你的網站,雙擊
雙擊目錄瀏覽,然後如下圖,點右側的啓用
再回去,啓動瀏覽,就顯示目錄了
二、新建Java項目
代碼如下:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ReadURLSource {
public static void main(String args[]) {
new NetWin();
}
}
class NetWin extends JFrame implements ActionListener, Runnable {
JButton button;
URL url;
JTextField inputURLText; // 輸入URL
JTextArea area;
byte b[] = new byte[118];
Thread thread;
NetWin() {
inputURLText = new JTextField(20);
area = new JTextArea(12, 12);
button = new JButton("確定");
button.addActionListener(this);
thread = new Thread(this);
JPanel p = new JPanel();
p.add(new JLabel("輸入網址:"));
p.add(inputURLText);
p.add(button);
add(area, BorderLayout.CENTER);
add(p, BorderLayout.NORTH);
setBounds(60, 60, 560, 300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if (!(thread.isAlive()))
thread = new Thread(this);
try {
thread.start();
} catch (Exception ee) {
inputURLText.setText("我正在讀取" + url);
}
}
public void run() {
try {
int n = -1;
area.setText(null);
String name = inputURLText.getText().trim();
url = new URL(name); // 使用字符串name創建url對象
String hostName = url.getHost(); // url調用getHost()
int urlPortNumber = url.getPort();
String fileName = url.getFile();
InputStream in = url.openStream(); // url調用方法返回一個輸入流
area.append("\n主機:" + hostName + "端口:" + urlPortNumber + "包含的文件名字:" + fileName);
area.append("\n文件的內容如下:");
while ((n = in.read(b)) != -1) {
String s = new String(b, 0, n);
area.append(s);
}
} catch (MalformedURLException e1) {
inputURLText.setText("" + e1);
return;
} catch (IOException e1) {
inputURLText.setText("" + e1);
return;
}
}
}
運行後彈出窗口
輸入剛纔網站瀏覽中的地址,後面加上/a.txt
完畢