import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
public class FileIOUtils {
// Read file using BufferedReader
public static List<String> readLines(String filename) throws IOException {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
return lines;
}
// Read entire file as string
public static String readFile(String filename) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}
// Write to file
public static void writeFile(String filename, String content) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(content);
}
}
// Write lines to file
public static void writeLines(String filename, List<String> lines) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
for (String line : lines) {
writer.write(line);
writer.newLine();
}
}
}
// Read using NIO.2
public static List<String> readLinesNIO(String filename) throws IOException {
Path path = Paths.get(filename);
return Files.readAllLines(path);
}
// Write using NIO.2
public static void writeFileNIO(String filename, String content) throws IOException {
Path path = Paths.get(filename);
Files.write(path, content.getBytes());
}
// Copy file
public static void copyFile(String source, String dest) throws IOException {
Path sourcePath = Paths.get(source);
Path destPath = Paths.get(dest);
Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
}
// Check if file exists
public static boolean fileExists(String filename) {
Path path = Paths.get(filename);
return Files.exists(path);
}
}