【问题标题】:Java Commons IO append multiple filesJava Commons IO 追加多个文件
【发布时间】:2023-03-26 00:59:01
【问题描述】:

我正在使用 Commons IO 从 Internet 下载文件。

这是我正在使用的方法:

public void getFile(String url){

File f = new File("C:/Users/Matthew/Desktop/hello.txt");
    PrintWriter pw = new PrintWriter(f);
    pw.close();
    URL url1;
    try {
        url1 = new URL(url);
        FileUtils.copyURLToFile(url1, f);
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    }catch (IOException e1){
        e1.printStackTrace();
    }
}

有没有办法我可以使用这种方法下载多个文件并将它们全部保存到 hello.txt 文件中?使用上述方法,所有内容都会被覆盖,最后下载的文件将是添加到 hello.txt 文件中的文件。

基本上,有没有一种方法可以将多个文件下载存储在一个文件中。

谢谢。

【问题讨论】:

  • system.setOut() 适用于管道,以防它看起来像你想要的 stackoverflow.com/questions/18669245/…
  • 是的,我知道 Commons IO 有一个附加项,您可以将其添加到方法中,但不能将其添加到 copyURLToFile 方法中。
  • 你还是没有回答我的问题;你使用 Java 7+ 吗?
  • 我确实回答了你的问题。阅读上文。

标签: java http file-io apache-commons-io


【解决方案1】:

没有办法使用FileUtils。但是,如果您想使用 Apache Commons,我建议您执行以下操作:

File f = new File("C:/Users/Matthew/Desktop/hello.txt");
URL url1;
try {
    url1 = new URL(url);
    IOUtils.copy(url1.openStream(), new FileOutputStream(f, true));
} catch (MalformedURLException e1) {
    e1.printStackTrace();
} catch (IOException e1) {
    e1.printStackTrace();
}

它或多或少做同样的事情,但在FileOutputStream 上使用附加模式。

【讨论】:

  • 我无法让它工作。我已经使用了你的方法,但它仍然没有附加到文件,它只是覆盖它。
  • @user3080860 哎呀!我忘了删除顶部的一行...对此感到抱歉。创建一个新的 PrintWriter 并关闭它会自动覆盖文件。 (我已经编辑了我的答案以删除该代码)。
猜你喜欢
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 2023-01-03
  • 2021-08-17
  • 1970-01-01
相关资源
最近更新 更多