File copy in java

File copy

Sometimes we need to copy the entire data of a text file into another text file. Stream are useful in this case. To understand how to use streams for copying a file content to another file, we can use the following logic:

For reading data from the input file, attach it to FileInputStream

For writing data into the output file, which is to be created, attach it to FileOutputStream

Now, read data from FileInputStream and write into FileOutputStream. This means, the data is read from the input file and send to output file.

Example
import java.io.*;
class test
{
public static void main(String args[])throws Exception
{
int ch;
FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1]);
while((ch=fin.read())!=-1)
fout.write(ch);
fin.close();
fout.close();
System.out.println(“1 file copied”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *