Question:
You are tasked with creating a program that reads data from a text file and writes the data to another file. The input file contains a list of names and their corresponding ages, formatted as follows:
John,23
Emily,19
Michael,27
Sara,21
Write a method copy_data(infile, outfile)
that takes two string parameters infile
and outfile
. The infile
parameter is the name of the input file and the outfile
parameter is the name of the output file. The method should read the data from the input file and write it to the output file in the same format.
For example, if the input file contains the data as shown above, then the output file should also contain the same data. Assume that both the input and output files already exist.
Write the complete copy_data(infile, outfile)
method to accomplish this task.
Example Usage:
copy_data("input.txt", "output.txt");
Answer:
public static void copy_data(String infile, String outfile) {
try {
// Create FileReader and FileWriter objects
FileReader reader = new FileReader(infile);
FileWriter writer = new FileWriter(outfile);
// Create BufferedReader and BufferedWriter objects
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
// Read the file line by line
String line;
while ((line = br.readLine()) != null) {
// Write the line to the output file
bw.write(line);
bw.newLine(); // Add a new line in the output file
}
// Close the file resources
br.close();
bw.close();
System.out.println("Data copied successfully!");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
Explanation:
copy_data
method takes infile
and outfile
as parameters.FileReader
object to read the data from the input file, and a FileWriter
object to write the data to the output file.BufferedReader
object to read the file line by line, and a BufferedWriter
object to write the data line by line.while
loop, we read each line from the input file using the readLine
method of BufferedReader
. If the line is not null
, we write it to the output file using the write
method of BufferedWriter
. Additionally, we add a new line using the newLine
method to separate the lines in the output file.close
method of both BufferedReader
and BufferedWriter
.catch
block and an appropriate error message is displayed.