dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Apr 21, 2021

Java: How to Copy a File Using FilesCopy

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

*/
Sridhar M S
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date