首页 > 其他 > 详细

使用Channel进行本地文件读写的简单实例

时间:2020-05-12 10:51:17      阅读:43      评论:0      收藏:0      [点我收藏+]

 

通过文件的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();

使用Channel进行本地文件读写的简单实例

原文:https://www.cnblogs.com/mc-74120/p/12874278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!