如何将资源复制到 Java 中另一个位置的文件

How to copy a resource to a file in another location in Java

我正在尝试将项目中的资源复制到磁盘上的另一个位置。到目前为止,我有这个代码:

if (!file.exists()){
    try {
        file.createNewFile();
        Files.copy(new InputSupplier<InputStream>() {
            public InputStream getInput() throws IOException {
                return Main.class.getResourceAsStream("/" + name);
            }
        }, file);                   
    } catch (IOException e) {
        file = null;
        return null;
    }
}

它工作正常,但 InputSupplier class 已被弃用,所以我想知道是否有更好的方法来完成我想做的事情。

查看 Guava 的文档 InputSupplier class:

For InputSupplier<? extends InputStream>, use ByteSource instead. For InputSupplier<? extends Reader>, use CharSource. Implementations of InputSupplier that don't fall into one of those categories do not benefit from any of the methods in common.io and should use a different interface. This interface is scheduled for removal in December 2015.

所以在你的情况下,你正在寻找 ByteSource:

Resources.asByteSource(url).copyTo(Files.asByteSink(file));

有关详细信息,请参阅 Guava Wiki 的 this section


如果您正在寻找纯 Java(无外部库)版本,您可以执行以下操作:

try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("/" + name)) {
    Files.copy(is, Paths.get("C:\some\file.txt"));
} catch (IOException e) {
    // An error occurred copying the resource
}

请注意,这仅适用于 Java 7 及更高版本。