CharBuffer:抽象类 通过CharBuffer.allocate()获取 HeapCharBuffer 类型 toString方法实现:new String(char[],开始位置,截取长度);
BtyeBuffer:抽象类,同上,通过Charset.newDecode()(返回CharsetDecode类).Decode(btyebuffer,charbuffer,true);进行转换, NIO对文件的操作如下:
import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; /** * @description 用于学习NIO * @author:jiemoren * @time: 2020/9/20 13:39 */ public class NioStudy { @Test public void nioRead(){ ByteBuffer byteBuffer=null; //这里为了节省执行时间使用StringBuilder //StringBuilder stringBuilder=new StringBuilder(); //为了节省系统扩容StringBuilder里char[]value的性能 File file=new File("C:\\Users\\MSI-NB\\Desktop\\服务和应用.bat"); StringBuilder stringBuilder=new StringBuilder((int) file.length()); try { //创建InputStream FileInputStream inputStream=new FileInputStream(file); //获取Channel FileChannel fileChannel=inputStream.getChannel(); //获取utf-8的字符编码集 Charset charset=Charset.forName("utf-8"); //通过utf-8字符编码集创建编码解析器 CharsetDecoder charsetDecoder=charset.newDecoder(); int capacity=1024; //这里使用直接内存,不归gc管,需要手动释放内存 byteBuffer=ByteBuffer.allocateDirect(capacity); //使用堆内存的方式 //byteBuffer=ByteBuffer.allocate(capacity); CharBuffer charBuffer=CharBuffer.allocate(capacity); int lenght=-1; while ((lenght=fileChannel.read(byteBuffer))!=-1){ charsetDecoder.decode(byteBuffer,charBuffer,true); //这里的toString()方法通过new String(char[] c.int start,int end)创建返回 stringBuilder.append(charBuffer.toString()); //情况buffer byteBuffer.clear(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //清除直接内存 ((DirectBuffer)byteBuffer).cleaner().clean(); } System.out.println(stringBuilder.toString()); } }
- MappedByteBuffer 类底层继承了ByteBuffer ,其核心为map方法实现把物理内存虚拟为运行内存,省略一次拷贝,直接拷贝给用户内存,从而跳过IO读写需要把物理内存加载到运行内存在拷贝到用户内存的两次拷贝过程
- class LargeMappedFiles {
- static int length = 0x8FFFFFF; //128MB
- public static void main(String[] args) throws Exception{
- MappedByteBuffer out = new RandomAccessFile("test.dat","rw").getChannel()
- .map(FileChannel.MapMode.READ_WRITE,0,length);
- for (int i = 0; i < length;i++){
- out.put((byte)'x');
- }
- System.out.print("Finished writing");
- for (int i = length/2; i<length/2+6;i++){
- System.out.print(out.get(i));
- }
- }
- }
BIO 文件操作
public static String bioRead(String fileName) throws IOException { long startTime = System.currentTimeMillis(); try { FileReader reader = new FileReader(fileName); StringBuffer buf = new StringBuffer();
//使用char字符流 //char[] cbuf = new char[BF_SIZE];
//使用字节流
byte []b=new btye[BF_SIZE] while (reader.read(b) != -1) {
//new String(byte[]b,int sart,int end);中使用
//实现了CharsetDecode的StringCoding来实现byte到char的转换
buf.append(new String(b,0,b.length)); } reader.close(); return buf.toString(); } finally { System.out.println("使用BIO读取文件耗时:" + (System.currentTimeMillis() - startTime) + "毫秒"); } }