使用 Java 从网页中提取数据?

新手上路,请多包涵

我正在尝试用 Java 编写我的第一个程序。目标是编写一个浏览网站并为我下载文件的程序。但是,我不知道如何使用 Java 与 Internet 进行交互。谁能告诉我要查找/阅读哪些主题或推荐一些好的资源?

原文由 user658168 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
1 个回答

最简单的解决方案(不依赖于任何第三方库或平台)是创建一个指向您要下载的网页/链接的 URL 实例,并使用流读取内容。

例如:

     import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;


    public class DownloadPage {

        public static void main(String[] args) throws IOException {

            // Make a URL to the web page
            URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

            // Get the input stream through URL Connection
            URLConnection con = url.openConnection();
            InputStream is = con.getInputStream();

            // Once you have the Input Stream, it's just plain old Java IO stuff.

            // For this case, since you are interested in getting plain-text web page
            // I'll use a reader and output the text content to System.out.

            // For binary content, it's better to directly read the bytes from stream and write
            // to the target file.

            try(BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
                String line = null;

                // read each line and write to System.out
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }
        }
    }

希望这可以帮助。

原文由 Yohan Liyanage 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题