Introduction to File Handling:
File handling in Java is typically done using classes from the java.io package. The key classes include
File, FileInputStream, FileOutputStream, BufferedReader,
and BufferedWriter.
Java File Handling: Reading and Writing Files
In Java, file handling is a crucial aspect of working with data. It involves reading from and writing to files on the file system. Let's explore the basics of file handling.
Reading from a File:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "path/to/your/file.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
Writing to a File:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "path/to/your/output.txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
// Write content to the file
writer.write("Hello, this is written to the file!");
} catch (IOException e) {
System.out.println("Error writing to the file: " + e.getMessage());
}
}
}
Note:
File handling in Java involves various classes and methods for different file operations. It is essential to handle exceptions and close file resources properly to avoid potential issues.