RandomAccessFile、FileChannel、MappedByteBuffer读写文件

代码:

package com.nio;

import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

import junit.framework.TestCase;

public class TestNIO extends TestCase {
	private static final int K = 0x400;
	
	private static final String FILE_PATH = "c:/nio.txt";

	private void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
				closeable = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void testWrite() {
		RandomAccessFile raf = null;
		FileChannel fc = null;
		Charset charset = Charset.defaultCharset();
		CharsetEncoder charsetEncoder = charset.newEncoder();

		try {
			raf = new RandomAccessFile(FILE_PATH, "rw");
			fc = raf.getChannel();
			MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, K);
			CharBuffer cb = CharBuffer.wrap("A".toCharArray());
			charsetEncoder.encode(cb, mbb, true);
			mbb.flip(); //encode后,mbb的指针不在0的地方,所以要flip
			fc.position(0);//从头开始写,这行代码可能多余,因为position可能一开始就在0
			for (int i = 0; i < K; i++) {
				fc.write(mbb); 
				mbb.flip(); //write后,mbb的指针不在0的地方,所以要flip
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(fc);
			close(raf);
		}
	}

	public void testRead() {
		RandomAccessFile raf = null;
		FileChannel fc = null;
		Charset charset = Charset.defaultCharset();
		CharsetDecoder charsetDecoder = charset.newDecoder();
		StringBuilder sb = new StringBuilder();

		try {
			raf = new RandomAccessFile(FILE_PATH, "rw");
			fc = raf.getChannel();
			MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, K);
			fc.position(0);//从头开始读,这行代码可能多余,因为position可能一开始就在0
			while (fc.read(mbb) != -1) {
				mbb.flip();//read后,mbb的指针不在0的地方,所以要flip
				CharBuffer cb = charsetDecoder.decode(mbb);
				mbb.flip();//decode后,mbb的指针不在0的地方,所以要flip
				sb.append(cb);
			}
			System.out.println(sb);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(fc);
			close(raf);
		}
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值