Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes.
FileInputStream Class
It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file.
FileInputStream fin = new FileInputStream(filename);
This creates a FileInputStream object fin given a filename to it from where it will copy the content or do read operation.
Methods used:
1. read(): This method is used to read a byte of data. It returns that byte as an integer value or return -1 if the end of file is reached.
2. close(): This method is used to close the FileInputStream.
FileOutputStream Class
It is a byte output stream class which helps in writing the bytes to a file. It provides different functions to write the data to a file.
FileOutputStream fout = new FileOutputStream(filename);
This creates a FileOutputStream object fout given a filename to which it will write the read content.
Methods used:
1. write(): This method is used to write a byte of data to the FileOutputStream.
2. close(): This method is used to close the FileInputStream.
File Class
File f = new File(filename);
This creates an File object named f, given a string object which is the file name or location path of that file which is to be accessed.
Note: If the filename given here does not exist, then the File class will create a new file of that name.
Example:
Java
import java.io.*;
import java.util.*;
public class CopyFromFileaToFileb {
public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
while ((n = in.read()) != - 1 ) {
out.write(n);
}
}
finally {
if (in != null ) {
in.close();
}
if (out != null ) {
out.close();
}
}
System.out.println( "File Copied" );
}
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.println(
"Enter the source filename from where you have to read/copy :" );
String a = sc.nextLine();
File x = new File(a);
System.out.println(
"Enter the destination filename where you have to write/paste :" );
String b = sc.nextLine();
File y = new File(b);
copyContent(x, y);
}
}
|
Output
Enter the source filename from where you have to read/copy :
sourcefile.txt
Enter the destination filename where you have to write/paste :
destinationfile.txt
File Copied
Source File
Source File
Destination File
Destination File
Last Updated :
26 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...