Files Read/Write
Reading Files:
- Using
BufferedReader(Older Approach): - Using
Files.readAllLines(Java 7 and later):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("path/to/your/file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
In this example, the BufferedReader is used to read the file line by line.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class ReadFileWithNIOExample {
public static void main(String[] args) {
try {
Path path = Paths.get("path/to/your/file.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
This example uses the Files.readAllLines method to read all lines of the file into a list of strings.
Writing Files:
- Using
BufferedWriter(Older Approach): - Using
Files.write(Java 7 and later):
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("path/to/your/output.txt"))) {
writer.write("Hello, World!");
writer.newLine();
writer.write("This is a new line.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}
This example uses the BufferedWriter to write text to a file.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Arrays;
public class WriteFileWithNIOExample {
public static void main(String[] args) {
try {
Path path = Paths.get("path/to/your/output.txt");
Files.write(path, Arrays.asList("Hello, World!", "This is a new line."));
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}
The Files.write method is used to write lines of text to a file.
Note:
- Always close resources (such as
BufferedReaderorBufferedWriter) using try-with-resources or explicitly in afinallyblock to ensure proper resource management. - Make sure to handle exceptions appropriately, especially when working with file I/O, as file operations may throw
IOException.
Choose the approach that fits your requirements and the Java version you are using. The java.nio.file package provides a more modern and flexible API for file operations in Java 7 and later.