Java Copy File Sample

If your Java program is dealing with files in any way, chances are you will need to to do a copy file operation at some point. Java gives you a few different options to copy a file. In this tutorial, we will focus on using FileInputStream and File.copy() to copy the contents of one file to another. I prefer the File.copy() method just because it’s much less code.


Java Copy File Sample Code [FileInputSteam]

The sample code below uses the FileInputStream to copy the contents of one file to a new file.

package com.jcd.java.tutorials.MavenProject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class JavaCopyFile 
{

	public static void main(String[] args) 
	{
		
		int len;
		
		//Define our Streams
		InputStream inputStream;
		OutputStream outputStream;
		
		//Define our input and out files
		String sourceFile1 = "C:\\Users\\Admin\\Documents\\Java\\fileSample1.txt";
		String destinationFile1 = "C:\\Users\\Admin\\Documents\\Java\\fileSample2.txt";

		try 
		{
			inputStream = new BufferedInputStream(new FileInputStream(sourceFile1));
			outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile1));
			byte[] myBuffer = new byte[1024];
			
			
			while ((len = inputStream.read(myBuffer)) > 0) 
			{
				outputStream.write(myBuffer, 0, len);
			}
			
			//Close the file handles
			inputStream.close();
			outputStream.close();
				
		} 
		catch(Exception ex) 
		{
			System.out.println("Exception: "+ex);
		}

	}

}


You can see before running our Java sample, we had a single text file in our folder.

Now after running our Java sample, we have the original file and a new copy (fileSample2.txt) of the original in our folder.


Java Copy File Sample Code [File.copy()]

Our next sample Java code uses the File.copy() method to copy one file to another.

public static void copyFileUsingFileClass() {
		
		//Define our input and out file objects
		File sourceFile1 = new File("C:\\Users\\Admin\\Documents\\Java\\fileSample1.txt");
		File destinationFile1 = new File("C:\\Users\\Admin\\Documents\\Java\\fileSample3.txt");
		
		try 
		{
			Files.copy(sourceFile1.toPath(), destinationFile1.toPath());
		}
		catch(Exception ex) 
		{
			System.out.println("Exception: "+ex);
		}
		
	}


Now after running our Java sample, we have the original file and a new copy (fileSample3.txt) of the original in our folder.


Add a Comment

Your email address will not be published. Required fields are marked *