In Java, File I/O operations are essential for reading from and writing to files. This topic covers how to perform various file operations in Java, such as reading from a file, writing to a file, and handling exceptions.
Reading from a File
To read from a file in Java, you can use the FileInputStream
and BufferedReader
classes. Here's an example code snippet to read from a file named "input.txt":
try {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Writing to a File
To write to a file in Java, you can use the FileOutputStream
and BufferedWriter
classes. Here's an example code snippet to write to a file named "output.txt":
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, World!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Handling Exceptions
It's important to handle exceptions when working with files in Java. Always wrap file operations in a try-catch
block to handle potential errors gracefully.
By understanding and using proper File I/O operations in Java, you can efficiently read and write data to and from files. This is an essential skill for any Java programmer.