NIO文件系统I/O 发表于 2017-04-04 | 分类于 Java NIO文件系统的一些操作创建文件1234public void createFile(String path) throws IOException { Path target = Paths.get(path); Files.createFile(target);} 删除文件1234public void deleteFile(String path) throws IOException { Path target = Paths.get(path); Files.delete(target);} 复制文件12345public void copyFile(String path1, String path2) throws IOException { Path source = Paths.get(path1); Path target = Paths.get(path2); Files.copy(source, target);} 读取文件1234567891011121314public 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;} 写文件123456789public 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(); }} 检测目录状态1234567891011121314151617public 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将来式调用1234567891011public 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回调式调用12345678910111213141516public 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()); } });}