NIO2を使ったファイルの読み書きメモ
Java7のNIO2を使った簡単なファイル読み書き例。
package example; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; public class Nio2Example { static final Charset utf8 = Charset.forName("UTF-8"); // NIO2でファイル読み込み public static List<String> read() throws IOException { Path path = Paths.get("C:/work/foo.txt"); List<String> lines = Files.readAllLines(path, utf8); for (String s : lines) System.out.println(s); return lines; } // NIO2でファイル書き込み public static void write(List<String> lines) throws IOException { Path path = Paths.get("C:/work/foo2.txt"); Files.write(path, lines, utf8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } public static void main(String[] args) throws IOException { write(read()); } }