dcsimg
 

Java: How to Copy a File Using FilesCopy

Wednesday Apr 21st 2021 by Sridhar M S

This short Java programming tip shows you how to make a copy of an existing file using the Files.copy method in a few short snippets of Java code.

How to Copy a File Using Files.copy in Java

With Java's NIO package it is simple to make a copy of a file. The Files.copy method, which has multiple overridden signatures, helps achieve this. Below is an example of how to use the copy(Path source, Path target, CopyOption... options)method:

Code sample:

*/

import java.nio.file.*;

public class CopyFileApp{

	public static void main(String []args){
		CopyFileApp copyFileApp = new CopyFileApp();
		copyFileApp.proceed();
	}

	private void proceed()
	{
		Path sourceFile = Paths.get("CopyFileApp.java");
		Path targetFile = Paths.get("CopyFileApp2.java");

		try {
			Files.copy(
				sourceFile, 
				targetFile,
				StandardCopyOption.REPLACE_EXISTING);
				
			System.out.println("CopyFileApp.java copied as CopyFileApp2.java");
			
		}catch (Exception exception) {
			System.err.println("Exception: " + exception);
		}    
	}

}

/*

Output:
$java CopyFileApp
CopyFileApp.java copied as CopyFileApp2.java

*/
Home
Mobile Site | Full Site