I'm trying to copy a resource in my project onto another location on the disk. So far, I have this code:
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;
}
}
And it works fine, but the InputSupplier
class is deprecated, so I was wondering if there was a better way to do what I'm trying to do.
See the documentation for the Guava InputSupplier
class :
For
InputSupplier<? extends InputStream>
InputSupplier<? extends InputStream>
, useByteSource
instead. ForInputSupplier<? extends Reader>
InputSupplier<? extends Reader>
, useCharSource
. Implementations ofInputSupplier
that don't fall into one of those categories do not benefit from any of the methods incommon.io
and should use a different interface. This interface is scheduled for removal in December 2015.
So in your case, you're looking for ByteSource
:
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
See this section of the Guava Wiki for more information.
If you're looking for a pure Java (no external libraries) version, you can do the following:
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
}
Note that this is only valid for Java 7 and higher.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.