// Read file line by line
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Write to file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Line 1");
writer.newLine();
writer.write("Line 2");
} catch (IOException e) {
e.printStackTrace();
}
// Read entire file with NIO.2
try {
Path path = Paths.get("input.txt");
List<String> lines = Files.readAllLines(path);
String content = String.join("\n", lines);
} catch (IOException e) {
e.printStackTrace();
}
// Write with NIO.2
try {
Path path = Paths.get("output.txt");
Files.write(path, "Hello World".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// Copy file
try {
Files.copy(
Paths.get("source.txt"),
Paths.get("dest.txt"),
StandardCopyOption.REPLACE_EXISTING
);
} catch (IOException e) {
e.printStackTrace();
}
// Read binary file
try (FileInputStream fis = new FileInputStream("image.jpg")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// Process bytes
}
} catch (IOException e) {
e.printStackTrace();
}