[Java] io nio nio2

io 即 input output 的簡稱
兩者的區別是資料流的方向
input:磁碟至記憶體
output:記憶體至磁碟

io:原始
nio:java 1.4
nio2:Java 7

讀取每行 read every line

String path = "C:/temp/sample.txt";

// io
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

// nio
Files.lines(Paths.get(path)).forEach(System.out::println);

讀取為字串 read as string

io 並無現成方法,一樣須靠 BufferedReader 再去拼接
nio 則直接呼叫完事

String path = "C:/temp/sample.txt";

// io

StringBuffer content = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
String line;
while ((line = br.readLine()) != null) {
    content.append(line);
}

String string = content.toString();

// nio
string = Files.readString(Paths.get(path));

列出一層子檔案 list sub files

String path = "C:/temp";

// io
File file = new File(path);
File[] subs = file.listFiles();
for (File sub : subs) {
    System.out.println(sub);
}

// nio
Files.list(Paths.get(path)).forEach(System.out::println);

列出所有子檔案

io 必須遞迴

public void test() {
    String path = "C:/temp";
    List<File> files = listAllFiles(new ArrayList(), path);
    for (File file : files) {
        System.out.println(file);
    }
}

public List<File> listAllFiles(List<File> fileList, String path) {
    File[] files = new File(path).listFiles();
    for (File file : files) {
        if (file.isFile()) {
            fileList.add(file);
        } else if (file.isDirectory()) {
            fileList.add(file);
            listAllFiles(fileList, file.getPath());
        }
    }
    return fileList;
}

nio

Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println(file);
        return FileVisitResult.CONTINUE;
    }
});

以上例子可以明顯看出 nio 搭配 Steam 與 Lambda,寫法更為俐落