Java Exercise
In this exercise, you will create a Java program that demonstrates how to work with files using the File
, FileReader
, and FileWriter
classes. First, you will create a text file and enter data into it using FileWriter
. Then, you will open the file to read its contents using FileReader
. This exercise will help you understand how to perform input/output (I/O) operations on text files in Java.
Instructions:
- Create a text file named
example.txt
using the FileWriter
class.
- Write some data to the file using
FileWriter
.
- Read the contents of the file using the
FileReader
class.
- Print the contents of the file to the console to verify that the data was read correctly.
This exercise will help you understand basic file input/output operations in Java, providing you with the tools to manipulate data in files and improve the interactivity of your Java programs.
View Example Code
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandling {
public static void main(String[] args) {
// Create a text file and write to it
try {
File file = new File("example.txt");
if (!file.exists()) {
file.createNewFile(); // Create file if it doesn't exist
}
FileWriter writer = new FileWriter(file);
writer.write("This is a sample file in Java.\nThis file contains multiple lines of text.");
writer.close(); // Close the writer
// Read the content of the file
FileReader reader = new FileReader(file);
int i;
StringBuilder content = new StringBuilder();
while ((i = reader.read()) != -1) {
content.append((char) i); // Append each character to StringBuilder
}
reader.close(); // Close the reader
// Print the file content
System.out.println("File content:");
System.out.println(content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
File Contents:
This is an example of a Java file.
This file contains several lines of text.
This program demonstrates how to work with files in Java using the File
, FileReader
, and FileWriter
classes. First, a file named example.txt
is created, written to using FileWriter
, and then the contents are read using FileReader
. When the program is run, the file contents are displayed in the console, providing an understanding of how to perform basic file input/output operations in Java.