Javatpoint Logo
Javatpoint Logo

Copy Content/ Data From One File to Another in Java

In Java, copying data from one file to another file is a very simple process. We use the File, FileInputStream, and FileOutputStream classes for copying data. Before implementing the code, let's understand all these three classes one by one.

File

File class is used to create an instance of the file from which we want to write or read bytes of data. We create an instance of the File class in the following way:

We pass the filename in which we want to perform the read/write operation. If the specified file doesn't exist, it creates a new file with the specified name.

FileInputStream Class

The FileInputStream is one of the most used and important byte input stream classes in Java. It is mainly used for reading bytes of data from a file. FileInputStream class provides several methods for reading data from the file.

We create an instance of the FileInputStream class in the following way:

We pass the file name to the constructor from which we want to read data.

We use the following two methods of the FileInputStream class for copying data from one file to another one.

  1. read() method
    The read() method plays an important role in reading data from the file. It returns bytes data as an integer, and when its pointer reaches the end of the file, it returns -1.
  2. close() method
    The close() method is used for closing the instance of the FileInputStream class.

FileOutputStream Class

The FileOutputStream is one of the most used and important byte output stream classes in Java. It is mainly used for writing bytes data into a file. FileOutputStream class provides several methods for writing data into the file.

We create an instance of the FileOutputStream class in the following way:

We pass the file name to the constructor in which we want to write data.

We use the following two methods of the FileOutputStream class for copying data from one file to another one.

  1. write() method
    The write() method plays an important role in writing data(bytes data) into the file
  2. close() method
    The close() method is used for closing the instance of the FileOutputStream class.

Let's implement the code for copying data from one file to another by using File, FileInputStream, and FileOutputStreamclasses.

FileExample.java

Output:

Copy Content/ Data From One File to Another in Java

Content of Text1.txt

Copy Content/ Data From One File to Another in Java

Content of Text2.txt (copied data)

Copy Content/ Data From One File to Another in Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA