下载网站上的所有pdf文件

时间:2015-05-16 16:21:38

标签: java network-programming

尝试下载网站上的所有pdf文件,但代码不正确。我想那里有一个更好的。无论如何它是这样的:

try {
        System.out.println("Download started");
        URL getURL = new URL("http://cs.lth.se/eda095/foerelaesningar/?no_cache=1");
        URL pdf;
        URLConnection urlC = getURL.openConnection();           

        InputStream is = urlC.getInputStream();

        BufferedReader buffRead = new BufferedReader(new InputStreamReader(is));

        FileOutputStream fos = null;

        byte[] b = new byte[1024];

        String line;
        double i = 1;
        int t = 1;

        int length;
        while((line = buffRead.readLine()) != null) {

            while((length = is.read(b)) > -1) {

                if(line.contains(".pdf")) {

                    pdf = new URL("http://fileadmin.cs.lth.se/cs/Education/EDA095/2015/lectures/" 
                    + "f" + i + "-" + t + "x" + t);


                    fos = new FileOutputStream(new File("fil" + i + "-" + t + "x" + t +  ".pdf"));
                    fos.write(b, 0, line.length());
                    i += 0.5;
                    t += 1;

                    if(t > 2) {
                        t = 1;
                    }
                }
            }
        }
        is.close();
        System.out.println("Download finished");
    } catch (MalformedURLException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

我得到的文件是损坏,但有没有更好的方法来下载PDF文件?因为在网站上的一些文件是f1-1x1,f1-2x2,f2-1x1 ..但是如果文件是donalds.pdf stack.pdf等..

所以问题是,如何让我的代码更好地下载所有的pdf文件?

1 个答案:

答案 0 :(得分:2)

基本上你要问:"我如何可靠地解析HTML;识别所有指向PDF文件的下载链接"。

其他任何东西(就像你现在拥有的东西;预测链接将如何/可能/应该是什么样子)将成为悲伤的源泉;因为您的网站有任何更新;或尝试在另一个不同的网站上运行您的代码很可能会失败。这是因为HTML很复杂,而且有很多种口味,你应该忘掉" easy"分析HTML内容的解决方案。

从这个意义上讲:学习如何使用HTML解析器;第一个起点可能是Which HTML Parser is the best?

相关问题