Search This Blog

Showing posts with label file copying. Show all posts
Showing posts with label file copying. Show all posts

How to Easily Copy a File to Another File or Location in Java

The Files class in java has many useful static methods to copy and move files, create temporary files or folders etc. To copy a file from one location to another in Java, there is a static method copy in Files class. The Files class is in java.nio.file package. The method Files.copy() takes three arguments (parameters) : Path of source file (as object of Path class), Path of destination file ( as object of Path class ) and an option parameter. The option parameter can be one of the following:

StandardCopyOption.REPLACE_EXISTING
If the target file exists, then the target file is replaced.

StandardCopyOption.COPY_ATTRIBUTES
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes
that are copied is platform and file system dependent and therefore unspecified.

StandardCopyOption.NOFOLLOW_LINKS
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.

You have to import java.nio.file.StandardCopyOption to use option parameters.

try{
File sourcefile=new File("audio.mp3");
File destination=new File(System.getProperty("java.io.tmpdir")+"\\temp.mp3");
Files.copy(sourcefile.toPath(),destination.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException ex) {
ex.printStackTrace();
}

For the copy method, there are two other overloaded method definitions. In one, instead of source file's path, inputstream is the first parameter and the rest are same. For the other overloaded definition, an outputstream object is the second parameter instead of destination path object and the rest are same.

Similarly, to move a file from one location to another, there is a method move() in Files class. The parameters of this method is also same as those of copy method.