以数据流方法读取网页内容的应用程序。程序运行时,网址从文本框中读取

    1. package ggg.demo;
    2. import javax.swing.*;
    3. import java.net.*;
    4. import java.awt.*;
    5. import java.awt.event.*;
    6. import java.io.*;
    7. public class TT {
    8. public static void main(String args[]) {
    9. new DownNetFile();
    10. }
    11. }
    12. class DownNetFile extends JFrame implements ActionListener {
    13. JTextField infield = new JTextField(30);
    14. JTextArea showArea = new JTextArea();
    15. JButton b = new JButton("download");
    16. JPanel p = new JPanel();
    17. DownNetFile() {
    18. super("read network text file application");
    19. Container con = this.getContentPane();
    20. p.add(infield);
    21. p.add(b);
    22. JScrollPane jsp = new JScrollPane(showArea);
    23. b.addActionListener(this);
    24. con.add(p,"North");
    25. con.add(jsp,"Center");
    26. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    27. setSize(500, 400);
    28. setVisible(true);
    29. }
    30. public void actionPerformed(ActionEvent e) {
    31. readByURL(infield.getText());
    32. }
    33. public void readByURL(String urlName) {
    34. try {
    35. URL url = new URL(urlName);//由网址创建 URL 对象
    36. URLConnection tc = url.openConnection();//获得 URLConnection 对象tc.connect();//设置网络连接
    37. InputStreamReader in = new InputStreamReader(tc.getInputStream());
    38. BufferedReader dis = new BufferedReader(in);//采用缓冲式输入
    39. String inline;
    40. while ((inline = dis.readLine()) != null) {
    41. showArea.append(inline + "\n");
    42. }
    43. dis.close();//网上资源使用结束后,数据流及时关闭
    44. }catch(MalformedURLException e){
    45. e.printStackTrace();
    46. }
    47. catch(IOException e){
    48. e.printStackTrace();
    49. }
    50. /*访问网上资源可能产生 MalformedURLException 和 IOException 异常*/
    51. }
    52. }