为了更体现面向对象的特点本人对原码作了一点修改
并作了一点注释,希望大家多提意见,共同学习
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.StringTokenizer;
import java.net.*;
class haike1 extends JFrame implements ActionListener{
JTextField tf;
JButton b1,b2;
JTextArea ta;
haike1(){
super("网站原码查看器");
this.setSize(400,200);
JPanel p = (JPanel)this.getContentPane();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
tf = new JTextField(20);
b1 = new JButton("查看");
b1.addActionListener(this);
b2 = new JButton("保存");
b2.addActionListener(this);
ta = new JTextArea(30,30);
p1.add(new JLabel("网址"));
p1.add(tf);
p1.add(b1);
p1.add(b2);
p.add(p1,BorderLayout.NORTH);
p.add(new JScrollPane(ta),BorderLayout.CENTER);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
String s = tf.getText().trim();
new url(s);//调用资源定位类
}
if(e.getSource()==b2){
String s = ta.getText().trim();
new jiexi(s);//调用解析类
}
}
public static void main(String stri[]){
new haike();}
}
class url{
url(String s){
try{
URL ur = new URL(s);
URLConnection uc = ur.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));//建立与网站的流通道
String s1 = null;
while((s1=br.readLine())!=null){
new haike1().ta.append(s1+"\n");}
br.close();}
catch(Exception bbb){
JOptionPane.showMessageDialog(null,"发生连接异常");}}
}
class jiexi{
jiexi(String s){
try{
JFileChooser fc = new JFileChooser();//文件选择器
int i = fc.showSaveDialog(null);//保存对话框
BufferedWriter bw = new BufferedWriter(new FileWriter(fc.getSelectedFile()));
PrintWriter pw = new PrintWriter(bw);
if(fc.getSelectedFile()!=null&&i==JFileChooser.APPROVE_OPTION){
StringTokenizer fenxi = new StringTokenizer(s,"\n");//解析
while(fenxi.hasMoreTokens()){
pw.println(fenxi.nextToken());}}}
catch(Exception bbb){
JOptionPane.showMessageDialog(null,"发生异常");}}
}