Java program to copy file using FileStreams

We can use the FileInputStream and FileOutputStream classes in Java to copy files from one location to another. For this, we must import some specific classes of the java.io package. So, for example, let us use the statement import java.io.*; to include the entire package; The main logic of copying a file is to read the file associated with the FileInputStream variable and write the read content to the file associated with the FileOutputStream variable.

Methods used in the program

  1. int read(); Read one byte of data. Exists in FileInputStream. Other versions of this method: int read(byte[] byte array) and int read(byte[] byte array, int offset, int length)
  2. void write(int b): Write one byte of data. Exists in FileOutputStream. Other versions of this method: void write(byte[] byte array) and void write(byte[] byte array, int offset, int length);
/* Program to copy a src file to destination.
The name of src file and dest file must be
provided using command line arguments where
args[0] is the name of source file and
args[1] is name of destination file */

import java.io.*;
class src2dest
{
	public static void main(String args[])
	throws FileNotFoundException,IOException
	{
		/* If file doesnot exist FileInputStream throws
		FileNotFoundException and read() write() throws
		IOException if I/O error occurs */
		FileInputStream fis = new FileInputStream(args[0]);

		/* assuming that the file exists and need not to be
		checked */
		FileOutputStream fos = new FileOutputStream(args[1]);

		int b;
		while ((b=fis.read()) != -1)
			fos.write(b);

		/* read() will readonly next int so we used while
		loop here in order to read upto end of file and
		keep writing the read int into dest file */
		fis.close();
		fos.close();
	}
}

 

Submit Your Programming Assignment Details