AP Computer Science Exam Question:
Explain the different file classes in Java and demonstrate their usage by writing a program that reads data from a file and writes it to another file using the appropriate file classes. Provide a detailed explanation of each step in your answer.
Answer:
import java.io.*;
public class FileExample {
public static void main(String[] args) {
try {
// Step 1: Create a File object to represent the input file
File inputFile = new File("input.txt");
// Step 2: Create a FileReader object to read from the input file
FileReader reader = new FileReader(inputFile);
// Step 3: Create a BufferedReader object to efficiently read text from the FileReader
BufferedReader bufferedReader = new BufferedReader(reader);
// Step 4: Create a File object to represent the output file
File outputFile = new File("output.txt");
// Step 5: Create a FileWriter object to write to the output file
FileWriter writer = new FileWriter(outputFile);
// Step 6: Create a BufferedWriter object to efficiently write text to the FileWriter
BufferedWriter bufferedWriter = new BufferedWriter(writer);
String line;
// Step 7: Read data from the input file and write it to the output file
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
// Step 8: Close the input and output streams
bufferedReader.close();
bufferedWriter.close();
System.out.println("Data has been successfully copied from input.txt to output.txt.");
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
Explanation:
Step 1: In this step, we create a File
object named inputFile
and point it to the input file "input.txt".
Step 2: Here, we create a FileReader
object named reader
to read from the input file.
Step 3: We create a BufferedReader
object named bufferedReader
which efficiently reads text from the FileReader
.
Step 4: We create a File
object named outputFile
and point it to the output file "output.txt".
Step 5: We create a FileWriter
object named writer
to write to the output file.
Step 6: We create a BufferedWriter
object named bufferedWriter
which efficiently writes text to the FileWriter
.
Step 7: In this step, we read the data from the input file line by line and write it to the output file using the BufferedWriter
.
Step 8: Finally, we close the input and output streams to release the resources and print a success message if the operation was successful. If any exceptions occur, we will catch and print an error message.
This program demonstrates the usage of file classes in Java to read and write data between files using efficient input and output streams.