这个小程序的实用性并不大,因为一般的浏览器都支持查看源代码,只是通过这个小程序巩固一下对Url,File,I/O等知识的掌握。
此程序在输入时不再需要加"http://",直接输www形式的网站地址即可,保存时需要加所保存类型的后缀,如:.html,.txt,.doc等,推荐使用.html。
程序运行后效果:
输入网址后,按“确定”,则会显示出网页的源代码,再按保存,则可选择保存路径保存。
(此小程序运行正确的前提是所使用电脑能上网)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class UrlConnectionTest {
public static void main(String[] args) {
new TestFrame();
}
}
class TestFrame extends JFrame implements ActionListener, Runnable {
byte[] b = new byte[118];
public TestFrame() {
setVisible(true);
setTitle("网页源代码获得器");
setSize(WIDTH, HEIGHT);
button = new JButton("确定");
sButton = new JButton("保存");
text = new JTextField(15);
area = new JTextArea(12, 12);
button.addActionListener(this);
sButton.addActionListener(this);
thread = new Thread();
panel = new JPanel();
panel.add(new JLabel("输入网址:"));
panel.add(text);
panel.add(button);
panel.add(sButton);
Container con = this.getContentPane();
con.add(panel, BorderLayout.NORTH);
con.add(new JScrollPane(area), BorderLayout.CENTER);
saveFD = new FileDialog(this, "保存", FileDialog.SAVE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
if ((!thread.isAlive())) {
thread = new Thread(this);
}
try {
thread.start();
} catch (Exception ee) {
JOptionPane.showMessageDialog(this, "正在获取,请稍后", "提示信息",
JOptionPane.ERROR_MESSAGE);
}
if (e.getSource() == sButton) {
saveFD.setVisible(true);
try {
File f1 = new File(saveFD.getDirectory(), saveFD.getFile());
BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
String gt = area.getText();
bw.write(gt, 0, gt.length());
bw.flush();
bw.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public void run() {
try {
int n = -1;
area.setText(null);
url = new URL(("http://" + text.getText()).trim());
InputStream is = url.openStream();
while (-1 != (n = is.read(b, 0, b.length))) {
String str = new String(b, 0, n);
area.append(str);
}
} catch (MalformedURLException e1) {
text.setText("" + e1);
return;
} catch (IOException e1) {
text.setText("" + e1);
return;
}
}
public static final int WIDTH = 420;
public static final int HEIGHT = 300;
private URL url;
private JButton button;
private JButton sButton;
private JTextField text;
private JTextArea area;
private Thread thread;
private JPanel panel;
private FileDialog saveFD;
}