Copy Content/ Data From One File to Another in JavaIn 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. FileFile 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 ClassThe 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.
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.
Let's implement the code for copying data from one file to another by using File, FileInputStream, and FileOutputStreamclasses. FileExample.java Output: Content of Text1.txt Content of Text2.txt (copied data) |