Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active January 15, 2016 12:54
Show Gist options
  • Select an option

  • Save simonwoo/49a0542f9b6615bfec7f to your computer and use it in GitHub Desktop.

Select an option

Save simonwoo/49a0542f9b6615bfec7f to your computer and use it in GitHub Desktop.

Java NIO2

目标

  • 能批量获取文件属性的文件系统接口,去掉和特定文件系统相关的API。
  • 提供一个套接字和文件都能进行异步I/O操作的API。
  • 通道功能。

Path

path代表文件系统的位置。JVM会把Path绑定到运行的物理位置上。 NIO2把位置的概念和物理文件系统的处理分的很开。物理文件系统的处理通常是由Files辅助类完成的。

说明
Path 路径信息
Path2 工具类
FileSystem 与文件系统交互的类
FileSystems 工具类

Example

// create a path
Path path = Paths.get("/Users/mac/simon");

// print information
System.out.println("file name:" + path.getFileName());

// list all the java files under this path
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "*.java")) {
    stream.forEach(child -> System.out.println(child.getFileName()));
} catch (IOException e) {
   
}
public class FindJavaVisitor extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        if (file.toString().endsWith(".java")) {
            System.out.println(file.getFileName());
        }

        return FileVisitResult.CONTINUE;
    }
}

 // list all the java file under this path and subPath
try {
    Files.walkFileTree(path, new FindJavaVisitor());
} catch (IOException e) {
    e.printStackTrace();
}

文件系统IO

说明
Files 复制移动删除文件的工具类
WatchService 监视文件变化的类
Path path = Paths.get("/Users/mac/simon/test.java");
try(BufferReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    string line;
    while((line = reader.readLine()) != null) {
        ...
    }
}

try(BufferWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOptionWRITE)) {
    writer.write("hello world");
}

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

如果流的实现只对使用者暴露字节这个层次的细节,则可以直接继承InputStream或OutputStream。 java流以字节流为基础在字节流的基础上通过过滤流来满足不同的需求。流加上字节数组的方式使用起来比较繁琐。更好的作法是javaNIO中缓冲区。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment