Consider the following code snippet:
import java.io.*;
public class FileExample {
public static void main(String[] args) {
try {
File file = new File("sample.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello, World!");
writer.close();
file = new File("sample.txt");
FileReader reader = new FileReader(file);
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explain the purpose of the above code, step-by-step, and describe how it interacts with files.
The given code demonstrates the usage of file classes in Java to write content to a file and then read its content.
First, the code imports the necessary classes from the java.io
package, which includes the File
, FileWriter
, and FileReader
.
Inside the main
method, a new File
object, file
, is created with the filename "sample.txt". This represents the file in which we will be writing the content.
The code then creates a FileWriter
object, writer
, using the file
object. This allows us to write data to the file.
The write
method of the writer
object is called with the string "Hello, World!" as its argument. This writes the specified content to the file.
After writing the content, the writer
is closed using the close
method. This is an important step to ensure that any resources associated with the writer
are released.
Next, a new File
object, file
, is created with the same filename "sample.txt". This represents the file from which we will be reading the content.
A FileReader
object, reader
, is created using the file
object. This allows us to read data from the file.
Inside a while
loop, the read
method of the reader
object is called. This reads the characters from the file one by one. The loop continues until the read
method returns -1, indicating the end of the file.
If a character is read, it is casted to a char
type and printed to the console using System.out.print
. This displays the content of the file.
Finally, the reader
is closed using the close
method.
The purpose of the code is to demonstrate the process of writing content to a file and then reading its content. It shows how to use the File
, FileWriter
, and FileReader
classes from the java.io
package to interact with files in Java.