This example illustrates how to copy contents from one
file to another file. This topic is related to the I/O (input/output) of
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
"/"for the UNIX root directory, or
"\\"for a Win32 UNC pathname, and
This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file.
copyfile(String srFile, String dtFile)
The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter
File f1 = new
File f2 = new File(dtFile);
and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter
InputStream in = new
OutputStream out = new FileOutputStream(f2);
and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file.
byte buf = new byte;
// For creating a byte type buffeR
out.write(buf, 0, len); // For writing to another specified file from buffer buf
Code of the Program :
Output of program:
Here the data of "Hello.java" file is copied to the Filterfile.txt file.
C:\nisha>java CopyFile a.java Filterfile.txt
You can even use this program for copying files from one hard drive to another hard drive.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.