File Handling in Java
Duration: 7 min
This module delves into the essential topic of file handling in Java, a fundamental skill for any Java developer. Understanding how to read from and write to files is crucial for tasks such as data persistence, logging, and configuration management. Mastery of these skills will enable you to build more robust and efficient applications.
Reading from a File
Reading from a file in Java can be accomplished using various classes such as FileReader, BufferedReader, and Scanner. The BufferedReader class is often preferred for its efficiency in reading text from an input stream, buffering characters, and providing methods to read text line by line.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine())!= null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}This will print the contents of example.txt line by line to the console.
Example output if example.txt contains:
Hello
World
Hello
World
Writing to a File
Writing to a file can be done using FileWriter and BufferedWriter classes. The BufferedWriter class is used to provide a convenient way to write text to a character output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {
bw.write("Hello");
bw.newLine();
bw.write("World");
} catch (IOException e) {
e.printStackTrace();
}
}
}💡 Tip: Always use try-with-resources to ensure that file resources are closed automatically, preventing resource leaks.
❓ What class is typically used for reading text from a file efficiently in Java?
❓ Which class is used for writing text to a file in Java?