[筆記] Java nio

nio 即 New io
效能較佳且更為方便

常用方法

//判斷
Files.exists(path);
Files.notExists(path);
Files.isDirectory(path);
Files.isExecutable(path);
Files.isHidden(path);
Files.isReadable(path);
Files.isRegularFile(path);
Files.isSameFile(path, path2);
Files.isSymbolicLink(path);
Files.isWritable(path);

//操作
Files.move(fromPath, toPath);
Files.move(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING);
Files.copy(fromPath, toPath);
Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING);
Files.delete(path);
Files.deleteIfExists(path);

//查找
Files.list(path);
Files.walk(path);
Files.walk(path, level);
Files.walkFileTree(path, SimpleFileVisitor);
Files.walkFileTree(path, optionSet, level, SimpleFileVisitor);
Files.find(path, level, matcher);

//讀取
Files.readAllBytes(path);
Files.readAllLines(path);
Files.readAllLines(toPath, charset);
Files.readString(path);
Files.readString(path, charset);
Files.lines(path);
Files.lines(path, charset);

//寫入
Files.write(path, bytes);
Files.write(path, bytes, StandardOpenOption.APPEND);
Files.write(path, lines);
Files.write(path, lines, StandardOpenOption.APPEND);
Files.write(path, lines, charset);
Files.write(path, lines, charset, StandardOpenOption.APPEND);
Files.writeString(path, charSequence);
Files.writeString(path, charSequence, StandardOpenOption.APPEND);
Files.writeString(path, charSequence, charset);
Files.writeString(path, charSequence, charset, StandardOpenOption.APPEND);

// StandardOpenOption
StandardOpenOption.WRITE
StandardOpenOption.APPEND
StandardOpenOption.TRUNCATE_EXISTING
StandardOpenOption.CREATE_NEW
StandardOpenOption.CREATE
StandardOpenOption.DELETE_ON_CLOSE
StandardOpenOption.SPARSE
StandardOpenOption.SYNC
StandardOpenOption.DSYNC
// 限制層數
Files.walkFileTree(Paths.get(path), Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println(file);
        return FileVisitResult.CONTINUE;
    }
});

// 全部
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;
    }
});

往往需要搭配 Steam 與 Lambda 才會好用,例如:

Files.find(path, 1, (p, basicFileAttributes) -> {
    if (Files.isDirectory(p)) {
        return false;
    }
    return true;
}).forEach(System.out::println);