Commons IO (Apache) copyURLToFile 不工作

Commons IO (Apache) copyURLToFile Not Working

我正在编写一些代码来自动从给定一组链接的网站下载文件。我可以通过传入网站来制作链接数组,但以下代码不起作用:

public static void downloadFiles(String[] links) {
    for (String link : links) {
        try {
            URL u = new URL(link);
            File f = new File("D:" + File.separator + "Java Programming" + File.separator + "File Downloader" + File.separator + "output" + File.separator + link.split("/")[link.split("/").length - 1]);
            //System.out.println(f.toString());
            FileUtils.copyURLToFile(u, f);
        } catch (Exception e) {}
    }
}

我已经将 commons-io-2.6.jar 文件导入到 eclipse 中并进行了在线研究,但找不到任何人提供解决方案。我已经尝试 运行 代码,无论是否已创建 output 目录,但在任何一种情况下都不会下载文件。帮助将不胜感激。

一个潜在的问题可能是您正在捕获异常而不以任何方式处理它,因此如果抛出异常,您不会以任何方式收到通知。尝试打印该异常的堆栈跟踪,看看是否抛出任何异常。

无论如何,对我有用的是使用 BufferedReaderBufferedWriter:

// Create URL object
URL url = new URL(singleUrl);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

File downloadedFile = new File(DOWNLOAD_FOLDER+generateFilename()+".html");

BufferedWriter writer = new BufferedWriter(new FileWriter(downloadedFile));

// read each line from stream till end
String line;
while ((line = reader.readLine()) != null) {
    writer.write(line);
}

reader.close();
writer.close();