CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES
[Link] FILE STREAMS
DATE:
AIM:
To write a java program to copy the contents of one file to another file
using file stream.
ALGORITHM:
1. Define a class named copyContent.
2. Inside the class, define a main method.
3. Create two String variables, sourceFile and destinationFile, and initialize
them with the names of the source and destination files, respectively.
4. Use a try block with resources to create a FileInputStream (fis) for the
source file and a FileOutputStream (fos) for the destination file.
5. Create a byte array named buffer with a size of 1024.
6. Use a while loop to read data from the FileInputStream into the buffer
array until the read method returns -1 (indicating the end of the file).
7. Inside the loop, write the data from the buffer array to the
FileOutputStream using the write method.
8. After the loop completes, print a message indicating that the file was
copied successfully.
9. Use a catch block to handle any IOException that may occur during the
file copying process and print an error message.
[Link] the FileInputStream and FileOutputStream resources in the finally
block to ensure they are properly closed, even if an exception occurs.
[Link] of the main method and the copyContent class.
PROGRAM:
import [Link];
import [Link];
import [Link];
REGISTER NO:2127220501098 PAGE NO:
CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES
class copyContent{
public static void main(String[] args) {
String sourceFile = new String("[Link]");
String destinationFile = new String("[Link]");
try(FileInputStream fis= new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile)){
int BufferReader;
byte[] buffer = new byte[1024];
while( (BufferReader = [Link](buffer))!=-1){
[Link](buffer,0,BufferReader);
}
[Link]("File copied to destination from source successfully");
}
catch(IOException e){
[Link]("Error" +[Link]());
}
}
}
SAMPLE INPUT AND OUTPUT:
[Link]:
This is the first line.
This is the second line.
This is the third line.
REGISTER NO:2127220501098 PAGE NO:
CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES
[Link]
This is the first line.
This is the second line.
This is the third line.
RESULT:
Thus the Java Program to copy contents of one file to another has been
successfully written and executed.
REGISTER NO:2127220501098 PAGE NO: