Copying file using FileStreams in Java
The main logic of copying a file is to read the file associated with FileInputStream variable and write the read contents into the file associated with FileOutputStream variable. We can copy a file from one location to another using FileInputStream and FileOutputStream classes in Java. Now before adhering forward let us discuss essential methods that will be used in the program.
Method 1: read(): Reads a byte of data. Present in FileInputStream.
Return type: An integer value
Syntax: Other versions
int read(byte bytearray or int read(byte bytearray, int offset, int length)
Method 2: write(int b): Writes a byte of data. Present in FileOutputStream
void write(byte bytearray) or void write(byte bytearray, int offset, int length)
Implementation: We will be creating two files named “demo.rtf” and “outputdemo.rtf” as another file where no content is there. Below is an image of the “demo.rtf” file as a sample input image.
- First, we will create two objects of the File class, one referring to FileInputClass and the other for FileOutputStream Class.
- Now we will create objects of FileInputStream class and FileOutputStream class prior to creating variables and assigning null to corresponding datatypes.
- Pass respective objects of FileInputStream and FileOutputStream objects
- Now using loops keep reading from a file and write it to another file using FileOuputStream using the read() and write() methods.
Tip: It is good practice to close the streams to avoid memory leakage.
Output: The same content will be reflected back in the “outputdemo.rtf” file as seen below in the “demo.rtf” file.
Output Explanation: The name of the src file and dest file must be provided using command line arguments where args is the name of the source file and args is the name of the destination file.
This article is contributed by Parul Dang. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.