1. Working with Files in Java
Java provides several classes for file handling. The most commonly used classes
for file handling are:
File: Represents the file or directory in the filesystem.
FileReader, FileWriter: For reading from and writing to text files.
BufferedReader, BufferedWriter: To improve performance when reading
from and writing to files by buffering the data.
FileInputStream, FileOutputStream: For reading from and writing to binary
files.
2. The File Class
The File class is used to create, delete, and check file and directory properties. It
can represent both files and directories.
Example:
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("example.txt");
// Check if the file exists
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
// Create a new file
try {
, if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
3. Reading from Files (FileReader and BufferedReader)
FileReader is used for reading character files.
BufferedReader is used to read text from a file efficiently by buffering the
input.
Example (FileReader and BufferedReader):
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}