【问题标题】:Copy file from jar and write to a file without storing in memory从 jar 复制文件并写入文件而不存储在内存中
【发布时间】:2015-12-09 18:06:52
【问题描述】:

我在 jar 文件中有一个文件,我需要将该文件复制并存储在一个目录中。我可以使用什么 java api 同时读取/写入文件而不必先将其缓存在内存中?

我知道如何从 jar 中单独复制文件,然后写入文件,但它首先将其缓存在内存中。

下面的答案看起来不是在内存中缓存,但我想知道缓存与非缓存在内存中的区别?

How to copy files out of the currently running jar

【问题讨论】:

  • 尝试answer 到您的链接问题。
  • @fscore 链接的代码没有做任何缓存,你在说什么?
  • @Andreas 你如何确定代码是否正在缓存?
  • @fscore 答案是使用一个小的 2k 缓冲区。那不是缓存。

标签: java file memory file-io jar


【解决方案1】:

这是一个使用内存缓存复制文件的简短示例:

    try {
        Path source = Paths.get(getClass().getClassLoader().getResource("resource").toURI());
        Path target = Paths.get("targetfile");

        // copy with in memory caching
        // read all bytes to memory
        byte[] data = Files.readAllBytes(source);
        // write bytes from memory to target file
        Files.write(target, data);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

同样的例子没有内存缓存:

    try {
        Path source = Paths.get(getClass().getClassLoader().getResource("resource").toURI());
        Path target = Paths.get("targetfile");

        // copy without in memory caching
        Files.copy(source, target);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

重要的区别在于,在第一种情况下,文件的完整内容被读取到一个字节数组中,该字节数组存储在内存中。根据文件的大小,这可能非常糟糕。在第二种情况下,复制操作知道源和目标,因此能够小部分复制文件,直到文件被完全复制。例如,一个人始终可以一次复制 2048 个字节,就像链接问题的已接受答案一样。

【讨论】:

  • 就“分配零内存”而言,这不是答案(此处分配是隐藏的),但提问者必须了解这一点
猜你喜欢
  • 2015-07-27
  • 2013-02-24
  • 2016-03-24
  • 2018-08-04
  • 1970-01-01
  • 2023-03-05
  • 2010-09-17
  • 2011-08-07
相关资源
最近更新 更多