通过文件的io类自带的Channe将读写的数据放入缓冲区进行操作 Channel负责传输,Buffer负责存储 使效率更高
将数据写入本地文件:
public static void main(String[] args) throws IOException {
String string="hello";
//创建一个输出流
FileOutputStream fileInputStream = new FileOutputStream("d:\\file01.txt");
//获取对应的FileChannel 真实类型为FileChannelImpl
FileChannel channel = fileInputStream.getChannel();
//创建一个缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//将str放入byteBuffer
byteBuffer.put(string.getBytes());
//对buffer进行反转
byteBuffer.flip();
//将buffer中数据写入FileChannel
channel.write(byteBuffer);
fileInputStream.close();
}
从本地文件读入数据:
public static void main(String[] args) throws IOException {
File file=new File("d:\\file01.txt");
//创建文件输入流
FileInputStream fileInputStream = new FileInputStream(file);
//通过outputStream获取FileChannel
FileChannel channel = fileInputStream.getChannel();
//创建缓冲区
ByteBuffer allocate = ByteBuffer.allocate((int) file.length());
//将通道中数据放入缓冲区
channel.read(allocate);
System.out.println(new String(allocate.array()));
fileInputStream.close();
原文:https://www.cnblogs.com/mc-74120/p/12874278.html