I have two Java.io.File objects file1 and file2. I want to copy the contents from file1 to file2. Is there an standard way to do this without me having to create a method that reads file1 and write to file2
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Since Java 7 you can use
Files.copy()
from Java's standard library.You can create a wrapper method:
that can be used in the following way:
No. Every long-time Java programmer has their own utility belt that includes such a method. Here's mine.
No, there is no built-in method to do that. The closest to what you want to accomplish is the
transferFrom
method fromFileOutputStream
, like so:And don't forget to handle exceptions and close everything in a
finally
block.Or use Files.copy(file1,file2) from Google's Guava library.
If you want to be lazy and get away with writing minimal code use
FileUtils.copyFile(src, dest)
from Apache IOCommonsIn Java 7 you can use
Files.copy()
and very important is: Do not forget to close the OutputStream after creating the new file.