【问题标题】:Read directly from a URL and write in a file - Java [duplicate]直接从 URL 读取并写入文件 - Java [重复]
【发布时间】:2015-08-04 08:24:29
【问题描述】:

我正在读取 URL 的内容并写入文件,问题是我无法写入文件中的所有内容,也不知道我做错了什么。

我的代码,

try {
            URL url = new URL(sourceUri);
            URLConnection conn = url.openConnection();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));


            file.getParentFile().mkdirs();
            file.createNewFile();

            FileWriter fw = new FileWriter(file);
            BufferedWriter bw  = new BufferedWriter(fw);

            while ((inputLine = br.readLine()) != null) {
                bw.write(inputLine + System.getProperty("line.separator"));
            }

            br.close();

            System.out.println("DONE");

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

        return ontologies;
    }

请帮忙

【问题讨论】:

  • 第一件事:使用 java.nio.file。第二:你确定这是一个文本文件吗?为什么不直接复制InputStream
  • @aioobe 不重复;当您在 2015 年拥有 java.nio.file 时,此答案使用过时的 API,请参阅我的答案。
  • @fge,我在链接的问题中没有看到任何提到过时 API 的内容。 (当然,有些答案使用的是过时的 API,但这里的正确程序是发布对 that 问题的答案,然后我认为将这个问题作为 dup 关闭。)
  • @aioobe 提示:File
  • @fge,我仍然没有在问题中看到任何File。仅仅因为答案已经过时并不意味着应该发布新问题。

标签: java file url


【解决方案1】:

你做错了很多事情。

首先:您不会关闭所有资源;文件的作者在哪里关闭?

第二:你使用new InputStreamReader(...)而不指定编码。说明另一端的编码是您的 JVM/OS 组合之一?

最后但并非最不重要的一点,其实这是最重要的,你应该使用 java.nio.file。毕竟这是 2015 年。

简单的解决方案:

final Path path = file.toPath(); // or rather use Path directly
Files.createDirectories(path.getParent());

try (
    final InputStream in = conn.getInputStream();
) {
    Files.copy(in, path);
}

完成,独立编码,关闭所有资源。

【讨论】:

【解决方案2】:

问题是您使用的是BufferedWriter 而您没有关闭它。他的缓冲区中有一些内容没有写入,而您丢失了。

尝试刷新缓冲区并关闭BufferedWriter

bw.flush();
bw.close();

br.close(); 之前添加这两行。

您还可以阅读BufferedWriter 的工作原理here

而且我认为您也应该关闭 FileWriter 以解除对文件的阻止。

fw.close();

编辑 1:

关闭BufferedWriter 将为您刷新缓冲区。您只需将其关闭即可。

【讨论】:

  • 你是对的,已编辑。
  • 非常感谢您的完美作品。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2016-05-20
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多