NIO文件系统I/O

NIO文件系统的一些操作

创建文件

1
2
3
4
public void createFile(String path) throws IOException {
Path target = Paths.get(path);
Files.createFile(target);
}

删除文件

1
2
3
4
public void deleteFile(String path) throws IOException {
Path target = Paths.get(path);
Files.delete(target);
}

复制文件

1
2
3
4
5
public void copyFile(String path1, String path2) throws IOException {
Path source = Paths.get(path1);
Path target = Paths.get(path2);
Files.copy(source, target);
}

读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public List<String> readFile(String path) {
Path target = Paths.get(path);
List<String> content = new ArrayList<>();
try {
BufferedReader reader = Files.newBufferedReader(target, StandardCharsets.UTF_8);
String line = "";
while ((line = reader.readLine()) != null) {
content.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

写文件

1
2
3
4
5
6
7
8
9
public void writeToFile(String content, String path) {
Path target = Paths.get(path);
try {
BufferedWriter writer = Files.newBufferedWriter(target, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}

检测目录状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void watchDir() {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = FileSystems.getDefault().getPath("/Users/bighandsome/Desktop");
WatchKey key = dir.register(watcher, ENTRY_MODIFY);
while (true) {
key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_MODIFY) {
System.out.println("dir change");
}
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

异步I/O将来式调用

1
2
3
4
5
6
7
8
9
10
11
public void futureIO(String path) throws IOException, ExecutionException, InterruptedException {
Path target = Paths.get(path);
AsynchronousFileChannel channel = AsynchronousFileChannel.open(target);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
Future<Integer> result = channel.read(buffer, 0);
while (!result.isDone()) {
System.out.println("do other thing");
}
Integer bytesRead = result.get();
System.out.println("Bytes read [" + bytesRead + "]");
}

异步I/O回调式调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void backIO(String path) throws IOException {
Path target = Paths.get(path);
AsynchronousFileChannel channel = AsynchronousFileChannel.open(target);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("finish");
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println(exc.getMessage());
}
});
}