Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard concise way to copy a file in Java?

Tags:

java

file

copy

It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution.

Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?

like image 819
Peter Avatar asked Sep 20 '08 01:09

Peter


People also ask

How do you copy a file in Java?

Another common way to copy a file with Java is by using the commons-io library. The latest version can be downloaded from Maven Central. Then, to copy a file we just need to use the copyFile() method defined in the FileUtils class. The method takes a source and a target file.


1 Answers

I would avoid the use of a mega api like apache commons. This is a simplistic operation and its built into the JDK in the new NIO package. It was kind of already linked to in a previous answer, but the key method in the NIO api are the new functions "transferTo" and "transferFrom".

http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#transferTo(long,%20long,%20java.nio.channels.WritableByteChannel)

One of the linked articles shows a great way on how to integrate this function into your code, using the transferFrom:

public static void copyFile(File sourceFile, File destFile) throws IOException {     if(!destFile.exists()) {         destFile.createNewFile();     }      FileChannel source = null;     FileChannel destination = null;      try {         source = new FileInputStream(sourceFile).getChannel();         destination = new FileOutputStream(destFile).getChannel();         destination.transferFrom(source, 0, source.size());     }     finally {         if(source != null) {             source.close();         }         if(destination != null) {             destination.close();         }     } } 

Learning NIO can be a little tricky, so you might want to just trust in this mechanic before going off and trying to learn NIO overnight. From personal experience it can be a very hard thing to learn if you don't have the experience and were introduced to IO via the java.io streams.

like image 91
3 revs, 3 users 73% Avatar answered Oct 12 '22 12:10

3 revs, 3 users 73%