Write a java program to Copy files


This Java code defines a class Copy_File with a main method that copies the contents of one file to another file using FileInputStream and FileOutputStream.

The program takes two command line arguments, which are the paths of the input file and the output file respectively. The try block creates a new FileInputStream object using the path of the input file, and a new FileOutputStream object using the path of the output file.

The program then reads the bytes from the input file using the read method of the FileInputStream class, and writes the bytes to the output file using the write method of the FileOutputStream class. This process continues until the end of the input file is reached (read returns -1).

Finally, the program closes both the input and output files using the close method of the respective classes, and prints a message indicating that the file has been successfully copied

If an exception occurs during the file copying process, the program catches the IOException and prints out an error message along with the exception object.

Source Code

import java.io.*;
public class Copy_File
{
	public static void main(String args[])
	{
		try
		{			
			FileInputStream sou_file = new FileInputStream(args[0]); //input file			
			FileOutputStream new_file = new FileOutputStream(args[1]);//output file			
			int byte_val;
 
			//read from first file and write to second file
			while ((byte_val = sou_file.read()) != -1)
			{				
				new_file.write(byte_val);
			}
 
			sou_file.close();
			new_file.close();
 
			System.out.println("File Copied successfully");
		}
		catch (IOException e)
		{
			System.out.println("Exception : " + e.toString());
		}
	}
}

Output

Run : java 06_Copy_File.java file.txt filecopy.txt
File Copied successfully