import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
/**
* NIO文件读写
*/
public class Client {
private static final String FILE_PATH = "C:\\Users\\xxx\\Desktop\\demo1.txt";
public static void read(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(FILE_PATH);
FileChannel channel = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer)!=-1) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
System.out.print((char) buffer.get());
}
}
}
public static void write(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
FileChannel channel = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world ".getBytes(StandardCharsets.UTF_8));
buffer.flip();
channel.write(buffer);
channel.close();
}
}
NIO代码示例
于 2023-12-13 15:19:03 首次发布