Monday, March 26, 2018

Java 7 easy file read and write

If you don't care about buffering, you could use this way to read and write fileswith Java 7:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadWrite {

 public static void main(String[] args) throws IOException {
  List lines = readAll("input.txt");
  writeAll("output.txt", lines);
 }

 private static List readAll(String input) throws IOException {
  return Files.readAllLines(Paths.get(input));
 }
 
 private static void writeAll(String output, List lines) throws IOException {
  Files.write(Paths.get(output), lines);
 }
}