Understanding File I/O in Java
Textual Information
In Java, File Input/Output is essential for reading from and writing to files.
Click this box to learn more.
Video Information
Code Snippets
See how File I/O is implemented in Java
import java.io.File; // Import the File class
import java.io.FileWriter; // Import the FileWriter class
import java.io.FileReader; // Import the FileReader class
import java.io.BufferedReader; // Import the BufferedReader class
import java.io.IOException; // Import the IOException class
//or do import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
File f = new File("example.txt");
// Writing to a file
try {
FileOutputStream fos = new FileOutputStream(f);
PrintWriter pw = new PrintWriter(fos);
pw.println("This is a first line.")
pw.println("This is a second line.")
pw.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
// Reading from a file
try {
FileReader fr = new FileReader(f);
BufferedReader bfr = new BufferedReader(fr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close(); // Close the reader
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
Quiz
Test your knowledge on File I/O in Java: