• 大文件读取通常使用FileChannel,本文介绍FileChannel按行读取文本实例 java


    大文件读取通常使用FileChannel,本文介绍FileChannel按行读取文本实例 java

    辅助类 dom

    public class FileReader {
    
    	private FileChannel fileChanne;
    
    	private String charset;
    
    	private ByteBuffer byteBuffer;
    
    	private int bufferSize;
    
    	public FileReader(FileChannel fileChannel, int bufferSize, String charset) {
    		this.fileChanne = fileChannel;
    		this.charset = charset;
    		this.bufferSize = bufferSize;
    		// byteBuffer = ByteBuffer.allocate(bufferSize) ;
    	}
    
    	public String readline() throws IOException {
    
    		if (byteBuffer == null) {
    			byteBuffer = ByteBuffer.allocate(bufferSize);
    
    			int len = fileChanne.read(byteBuffer);
    
    			if (len == -1)
    				return null;
    
    			byteBuffer.flip();
    		}
    
    		byte[] bb = new byte[bufferSize];
    
    		int i = 0;
    
    		while (true) {
    
    			while (byteBuffer.hasRemaining()) {
    
    				byte b = byteBuffer.get();
    
    				if ('\r' == b || '\n' == b) {
    
    					if (byteBuffer.hasRemaining()) {
    						byte n = byteBuffer.get();
    
    						if ('\n' != n) {
    							byteBuffer.position(byteBuffer.position() - 1);
    						}
    
    					} else {
    
    						byteBuffer.clear();
    
    						int len = fileChanne.read(byteBuffer);
    
    						byteBuffer.flip();
    
    						if (len != -1) {
    							byte n = byteBuffer.get();
    
    							if ('\n' != n) {
    								byteBuffer.position(byteBuffer.position() - 1);
    							}
    						}
    
    					}
    
    					return new String(bb, 0, i, charset);
    
    				} else {
    
    					if (i >= bb.length) {
    
    						bb = Arrays.copyOf(bb, bb.length + bufferSize + 1);
    					}
    
    					bb[i++] = b;
    				}
    
    			}
    
    			byteBuffer.clear();
    			int len = fileChanne.read(byteBuffer);
    			byteBuffer.flip();
    
    			if (len == -1 && i == 0) {
    				return null;
    			}
    
    		}
    
    	}
    
    	public void close() throws IOException {
    		this.fileChanne.close();
    	}
    
    }

    使用例子

    FileChannel fileChannel  = new RandomAccessFile("/bigfile", "r").getChannel();
    		 
    		 FileReader fileReader = new FileReader(fileChannel, 1024, "utf-8") ;
    		 String line ;
    		 
    		 while(  ( line = fileReader.readline() ) != null ){
    			 
    			 System.out.println(line );
    			 
    		 }
    		 
    		 
    		 fileReader.close() ;
  • 相关阅读:
    广西建筑模板厂家批发——能强优品木业
    burp suite 2022下载及安装使用教程
    把二叉搜索树转换为累加树
    【Linux】如何创建yum 组(yum groups)
    部署Docker私有镜像仓库Harbor
    GitLab 知识树(二):gitlab社区版安装
    DevEco Studio如何安装中文插件
    webpack快速入门
    Java:Visual Studio Code在Java中大放异彩
    Spring-day02 容器的概念,容器中的对象,IOP入门
  • 原文地址:https://blog.csdn.net/heikeb/article/details/127429746