FileChannel之文件输入输出

1.文件的输入。

文件->读到文件流->文件通道->映射到内存->写入一个字符数组

File->FileInputStream->FileChannel->MappedByteBuffer->data[]


package IO_Operation;

import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {
	public static void main(String[] args)throws Exception {
		File file = new File("d:"+File.separator+"users.txt");
		FileInputStream input = null; //文件输入流
		input = new FileInputStream(file);
		FileChannel fin = null; //输入的通道对象
		fin = input.getChannel();
		MappedByteBuffer mbb = null; //文件的内存映射
		mbb = fin.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		byte data[] = new byte[(int)file.length()];
		int foot = 0;
		while (mbb.hasRemaining()) {
			data[foot++] = mbb.get();
		}
		System.out.println(new String(data));
		fin.close();
		input.close();
	}
}


2.文件的输出

新建一个文件->文件输出流->得到文件输出通道->开辟buf->向buf写数据->文件输出管道输出buf

package IO_Operation;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo2 {
	public static void main(String[] args) throws Exception{
		String info[] = {"aaa","bbb","ccc","ddd"};//待输出的数据
		File file = new File("d:"+File.separator+"out.txt");
		FileOutputStream output = null;
		output =new FileOutputStream(file);
		FileChannel fout = null;
		fout = output.getChannel();
		ByteBuffer buf = ByteBuffer.allocate(1024);
		for (int i = 0; i < info.length; i++) {
			buf.put(info[i].getBytes());
		}
		buf.flip();
		fout.write(buf);
		fout.close();
		output.close();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值