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); } } }
相关文章推荐
- [cocos2d-x 3.0] 触摸显示器
- [swift]可选类型
- 【Android-011】【多线程下载】
- Android防止键盘弹出后顶起布局
- Android防止键盘弹出后顶起布局
- android 教你制作音乐播放器
- [iOS]应用内切换语言,本地化,国际化
- Android自定义View和自定义属性
- IOS多线程
- Object-C 关键字之property,assign,copy,retain,release
- 8 个最优秀的 Android Studio 插件
- iOS远程推送
- Android更新前台服务的Notification中的ImageView不成功
- android多媒体的一些问题
- App调试内存泄露之Cursor篇
- IOS推送声音
- WebView简单使用
- 八款android日历 [Calendar] 开源项目框架分类总汇
- 七款android地图 [Map] 开源项目框架分类总汇
- Android5.1--SystemServer进程