您的位置:首页 > 移动开发

RandomAccessFile、FileChannel、MappedByteBuffer读写文件

2015-10-13 16:50 274 查看
s

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);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: