向文件写入示例
public class WriteTest {
public static void main(String[] args) {
Path path = Paths.get("D:/onJava8/test.txt");
try {
AsynchronousFileChannel writeFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
long position = 4;
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("com.king.java8+今天打老虎".getBytes());
buffer.flip();
Future<Integer> writeOperation = writeFileChannel.write(buffer, position);
buffer.clear();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取文件内容
public class ReadTest {
public static void main(String[] args) throws IOException {
List<String> collect = Files.readAllLines(Paths.get("D:/onJava8/test.txt"))
.stream()
.collect(Collectors.toList());
Files.write(Paths.get("D:/onJava8/test2.txt"), collect);
}
}