ITeye博客

以最快的速度获取文本行数(使用Java)

silent2N · 2010-12-13 11:46 · 编程语言 · Markdown

业务场景:用户通过浏览器上传文件,后台须判断此文本文件的行数是否超过限制(50行)

涉及技术:Apache表单文件,JDK的io

代码片段:


        //判断文件行数,formFile是表单文件类org.apache.struts.upload.FormFile
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(formFile.getInputStream()));
        lnr.skip(formFile.getFileSize());
        if(lnr.getLineNumber() + 1 >= 50) {
            //err输出“文件行数不能超过50行!”
        }
        lnr.close();

优缺点:我认为优点是不用遍历了,缺点不能辨别空白行

小弟抛砖引玉,大家评论下这段代码吧,说说如何用Java最有效率的获取文本行数

评论(60)

  1. #60 楼 · ldbjakyo · 2011-01-07 16:39

    说个问题,LineNumberReader 只是个 Java提供的 装饰器 ,该遍历还是遍历的

  2. #59 楼 · mercyblitz · 2010-12-27 01:17
  3. #58 楼 · yangyi · 2010-12-26 10:49
  4. #57 楼 · wezly · 2010-12-17 09:57
  5. #56 楼 · yangyi · 2010-12-16 20:33
  6. #55 楼 · wezly · 2010-12-16 09:39

    public class LineCounter {

    public static void main(String args) throws Exception{
    	File file = new File(args);
    	int bufferSize = 32768;
    	//Fix buffer size, let's test thread number
    	for(int i=1;i<100;i++){
    		long start = System.currentTimeMillis();
    		long result = calculate(file, i, bufferSize);
    		long used = System.currentTimeMillis() - start;
    		System.out.println("Thread number:"+i+"\tTime cost:"+used);
    	}
    	System.out.println("------------------I am the separator---------------------");
    	//Fix thread Number test buffer size
    	int threads = Runtime.getRuntime().availableProcessors();
    	for(int i=1;i<Integer.MAX_VALUE >>> 1;i<<=1){
    		long start = System.currentTimeMillis();
    		long result = calculate(file, threads, i);
    		long used = System.currentTimeMillis() - start;
    		System.out.println("Buffer size:"+i+"\tTime cost:"+used);
    	}
    		
    }
    
    private static class FilePartCallable implements Callable<Long>{
    	private int bufferSize;
    	private File file;
    	private long start;
    	private long count;
    	
    	public FilePartCallable(File file, long start, long count, int bufferSize){
    		this.file = file;
    		this.start = start;
    		this.count = count;
    		this.bufferSize = bufferSize;
    	}
    	
    	private long read(File file, long start, long count) throws IOException{
    		if(count == 0){
    			return 0;
    		}
    		RandomAccessFile raf = new RandomAccessFile(file, "r");
    		raf.seek(start);
    		
    		int len = count < bufferSize ? (int)count : bufferSize;
    		long lines = 0L,c=count/len;
    		byte buffer = new byte;
    		
    		for(int i=0;i<c;i++){
    			raf.read(buffer);
    			for(int j=0;j<len;j++){
    				if(buffer == '\n'){
    					lines++;
    				}
    			}
    		}
    		int rest = (int)(count%len);
    		raf.read(buffer,0, rest);
    		for(int j=0;j<rest;j++){
    			if(buffer == '\n'){
    				lines++;
    			}
    		}
    		raf.close();
    		return lines;
    	}
    	
    	public Long call() throws Exception {
    		return Long.valueOf(read(file, start, count));
    	}
    }
    
    private static long calculate(File file, int threads, int bufferSize) throws Exception{
    	ExecutorService es = Executors.newFixedThreadPool(threads);
    	CompletionService<Long> cs = new ExecutorCompletionService<Long>(es);
    	long size = file.length();
    	
    	long count = size/threads;
    	
    	for(int i=0;i<threads;i++){
    		long start = count*i;
    		cs.submit(new FilePartCallable(file, start, count, bufferSize));
    	}
    	
    	long start = count*threads;
    	long restCount = size - start;
    	cs.submit(new FilePartCallable(file, start, restCount, bufferSize));
    	
    	long lines = 0L;
    	for(int i=0;i<threads+1;i++){
    		lines += cs.take().get();
    	}
    	
    	es.shutdown();
    	return lines + 1;
    } 
    

    }

  7. #54 楼 · yangyi · 2010-12-15 21:19

    Let's speak with numbers: LineCounter可以比lz的结果快十倍以上,如果core多一些还可以更快

    
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.concurrent.Callable;
    import java.util.concurrent.CompletionService;
    import java.util.concurrent.ExecutorCompletionService;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class LineCounter {
    	
    	public static void main(String[] args) throws Exception{
    		File file = new File(args[0]);
    		int bufferSize = 32768;
    		//Fix buffer size, let's test thread number
    		for(int i=1;i<100;i++){
    			long start = System.currentTimeMillis();
    			long result = calculate(file, i, bufferSize);
    			long used = System.currentTimeMillis() - start;
    			System.out.println("Thread number:"+i+"\tTime cost:"+used);
    		}
    		System.out.println("------------------I am the separator---------------------");
    		//Fix thread Number test buffer size
    		int threads = Runtime.getRuntime().availableProcessors();
    		for(int i=1;i<Integer.MAX_VALUE >>> 1;i<<=1){
    			long start = System.currentTimeMillis();
    			long result = calculate(file, threads, i);
    			long used = System.currentTimeMillis() - start;
    			System.out.println("Buffer size:"+i+"\tTime cost:"+used);
    		}
    			
    	}
    	
    	private static class FilePartCallable implements Callable<Long>{
    		private int bufferSize;
    		private File file;
    		private long start;
    		private long count;
    		
    		public FilePartCallable(File file, long start, long count, int bufferSize){
    			this.file = file;
    			this.start = start;
    			this.count = count;
    			this.bufferSize = bufferSize;
    		}
    		
    		private long read(File file, long start, long count) throws IOException{
    			if(count == 0){
    				return 0;
    			}
    			RandomAccessFile raf = new RandomAccessFile(file, "r");
    			raf.seek(start);
    			
    			int len = count < bufferSize ? (int)count : bufferSize;
    			long lines = 0L,c=count/len;
    			byte[] buffer = new byte[len];
    			
    			for(int i=0;i<c;i++){
    				raf.read(buffer);
    				for(int j=0;j<len;j++){
    					if(buffer[j] == '\n'){
    						lines++;
    					}
    				}
    			}
    			int rest = (int)(count%len);
    			raf.read(buffer,0, rest);
    			for(int j=0;j<rest;j++){
    				if(buffer[j] == '\n'){
    					lines++;
    				}
    			}
    			raf.close();
    			return lines;
    		}
    		
    		public Long call() throws Exception {
    			return Long.valueOf(read(file, start, count));
    		}
    	}
    	
    	private static long calculate(File file, int threads, int bufferSize) throws Exception{
    		ExecutorService es = Executors.newFixedThreadPool(threads);
    		CompletionService<Long> cs = new ExecutorCompletionService<Long>(es);
    		long size = file.length();
    		
    		long count = size/threads;
    		
    		for(int i=0;i<threads;i++){
    			long start = count*i;
    			cs.submit(new FilePartCallable(file, start, count, bufferSize));
    		}
    		
    		long start = count*threads;
    		long restCount = size - start;
    		cs.submit(new FilePartCallable(file, start, restCount, bufferSize));
    		
    		long lines = 0L;
    		for(int i=0;i<threads+1;i++){
    			lines += cs.take().get();
    		}
    		
    		es.shutdown();
    		return lines + 1;
    	} 
    }
    
    
  8. #53 楼 · yangyi · 2010-12-15 19:50
  9. #52 楼 · wezly · 2010-12-15 17:25
  10. #51 楼 · smildlzj · 2010-12-15 11:06

    又被评为新手贴啊..

    我觉得这贴还不错啊..说得还比较底层..

  11. #50 楼 · zhangcong170 · 2010-12-14 10:12

    mercyblitz writes:

    [quote=zhangcong170][quote=mercyblitz][quote=zhangcong170][quote=mercyblitz]文件如果有2G,你怎么统计?[/quote] 可以用nio的文件通道,读取一部分数据到内存,记住此时的位置,统计行数,再读取一部分数据,再累加行数,直到文件数据全部被读取完,返回行数就OK了[/quote]

    用随机文件操作,比较合适![/quote] FileChannel本身就提供随机文件操作[/quote]

    你误解了,随机文件存取,比如在Java中,java.io.RandomAccessFile可以通过BIO和NIO的方式操作,但是本质通过FD(文件描述器,Java中的类为java.io.FileDescriptor),和方式没有关系。

    建议看一下RandomAccessFile的源码!

    恩 我只关注FileChannel了,就这个问题来看,实际上还是随机文件的存取
    关注点不一样

  12. #49 楼 · yangyi · 2010-12-14 07:58

    william_ai writes:

    [quote=night_stalker]还双核…… 纯扯蛋…… 试试看就知道多 sb 了,10 万行文件用 wc -l 比启动 jvm 还快。

    [b]磁盘比 CPU 慢一万倍[/b],用顺序读 BufferedInputStream 单线程就够了。 [/quote] 提倡用wc -l实现功能。在Linux和unix上 wc -l 更实用和高效一些。甚至,可以组合awk,sort,uniq,sed,eval,grep,find,split,xargs等实现极其复杂的功能。而且,大多数时候一行代码就可以搞定很复杂东西,这是件很爽的事情。 但是,还有一个问题,在windows平台怎么办呢? 最后,在javaeye谈谈技术,扯扯淡是件很happy的事情。

    各位大侠说得有道理,但是就算是wc -l那也是最后落实到系统调用上,只要没有数量级的差别就不能说是瓶颈吧,说JVM成了瓶颈有点太夸张了。 我的程序之所以慢是因为每次读一个byte,都有IO操作,改成buffer,就是read byte array后就变成几毫秒了,但是双核仍然比单核快50%以上,为免误导他人,特此声明。:) 看了一下bufferedReader的实现,也是提前预读一些byte到内存。这里让我不解的是,很多InputStream实现都是一个一个字节的读,岂不是很慢,看来我之前认为JVM会有缓冲的想法是极其错误的。 另外更正是硬盘比内存慢,而不是比CPU慢 但是buffer的数量是多大还是值得探讨的问题,要考虑现有的可用内存数量和分块的大小等

  13. #48 楼 · william_ai · 2010-12-14 07:31

    night_stalker writes:

    还双核…… 纯扯蛋…… 试试看就知道多 sb 了,10 万行文件用 wc -l 比启动 jvm 还快。

    [b]磁盘比 CPU 慢一万倍[/b],用顺序读 BufferedInputStream 单线程就够了。

    提倡用wc -l实现功能。在Linux和unix上 wc -l 更实用和高效一些。甚至,可以组合awk,sort,uniq,sed,eval,grep,find,split,xargs等实现极其复杂的功能。而且,大多数时候一行代码就可以搞定很复杂东西,这是件很爽的事情。
    但是,还有一个问题,在windows平台怎么办呢?
    最后,在javaeye谈谈技术,扯扯淡是件很happy的事情。
    
  14. #47 楼 · kraft · 2010-12-14 01:16

    一般的情况只要单线程顺序读统计\n个数就可以了, 但是要优化一次读取bufer的size, 或者交给java做。深入这个问题的话,要看这个文件具体是怎么存储的,不同的存储形式,分区格式,操作系统都有影响

  15. #46 楼 · seeker · 2010-12-14 00:31

    同事开始还不相信,用了一堆的方法去想快一点,俺说试一下readline,看了结果后他也不得不相信,也许有时最笨的方法就是最快的方法哈,呵呵

  16. #45 楼 · seeker · 2010-12-14 00:29

    俺只试过readline,200多万行,读出这个count,t400上2秒多,同事的dell双核,大约前年的机器,慢点,也只要4秒多

  17. #44 楼 · night_stalker · 2010-12-14 00:21

    还双核…… 纯扯蛋…… 试试看就知道多 sb 了,10 万行文件用 wc -l 比启动 jvm 还快。

    磁盘比 CPU 慢一万倍,用顺序读 BufferedInputStream 单线程就够了。

  18. #43 楼 · mercyblitz · 2010-12-13 23:41

    yangyi writes:

    [quote=javeaye][quote=mercyblitz][quote=javeaye][quote=mercyblitz][quote=yangyi]1 获取文件字节数 M 2 设定指针数量 N,使得 M > N 3 根据随机位置,指向文件的不同位置,按照M/N的长度遍历,当遇到'\n'时,换行计数+1 4 注意最后的M%N部分也要进行检查 [code=java] import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;

    public class LineCounter { public static void main(String[] args) throws Exception{ File file = new File(args[0]); int threads = Runtime.getRuntime().availableProcessors(); long size = file.length(); System.out.println(calculate(file, size, threads)); }

    private static class FilePartCallable implements Callable{ private File file; private long start; private long count;

      public FilePartCallable(File file, long start, long count){
      	this.file = file;
      	this.start = start;
      	this.count = count;
      }
    	
      private long read(File file, long start, long count) throws IOException{
      	RandomAccessFile raf = new RandomAccessFile(file, "r");
      	raf.seek(start);
      	long lines = 0L;
      	for(long i=0;i<count;i++){
      		if(raf.readByte() == '\n'){
      			lines++;
      		}
      	}
      	raf.close();
      	return lines;
      }
    	
      public Long call() throws Exception {
      	return Long.valueOf(read(file, start, count));
      }
    

    }

    private static long calculate(File file, long size, int threads) throws Exception{ ExecutorService es = Executors.newFixedThreadPool(threads); CompletionService cs = new ExecutorCompletionService(es);

      long count = size/threads;
    	
      for(int i=0;i<threads;i++){
      	long start = count*i;
      	cs.submit(new FilePartCallable(file, start, count));
      }
    	
      long start = count*threads;
      long restCount = size - start;
      cs.submit(new FilePartCallable(file, start, restCount));
    	
      long lines = 0L;
      for(int i=0;i<threads+1;i++){
      	lines += cs.take().get();
      }
    	
      es.shutdown();
      return lines + 1;
    

    } } [/code] [/quote]

    这个实现不错,不过呢,太浪费了,N个处理器只有N个线程,呵呵![/quote] 单个文件的话,分片,然后多线程统计每片。求和。

    多个文件的话,排队。[/quote]

    多个文件一起来也没有关系的,会达到最终一致的,前提是原子计数和能够开启那么多的FD。[/quote] 没问题,有个pool,要排队。 如果多个pool,context切换要消耗掉一部分资源。[/quote] 这部分工作交给线程池和它内置的队列来完成就可以了,按照CPU计数是因为这种Filter字节是很耗CPU的,基本上不是任务越多越好,另外也可以节约FD。经测试,PC上10万行的文件,双核用时7秒左右,单核10秒多

    确实不是越多与好,不过,要看具体情况,线程数和FD的话,可以通过内核设置来做。

  19. #42 楼 · yangyi · 2010-12-13 23:06

    javeaye writes:

    [quote=mercyblitz][quote=javeaye][quote=mercyblitz][quote=yangyi]1 获取文件字节数 M 2 设定指针数量 N,使得 M > N 3 根据随机位置,指向文件的不同位置,按照M/N的长度遍历,当遇到'\n'时,换行计数+1 4 注意最后的M%N部分也要进行检查 [code=java] import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;

    public class LineCounter { public static void main(String[] args) throws Exception{ File file = new File(args[0]); int threads = Runtime.getRuntime().availableProcessors(); long size = file.length(); System.out.println(calculate(file, size, threads)); }

    private static class FilePartCallable implements Callable{ private File file; private long start; private long count;

      public FilePartCallable(File file, long start, long count){
      	this.file = file;
      	this.start = start;
      	this.count = count;
      }
    	
      private long read(File file, long start, long count) throws IOException{
      	RandomAccessFile raf = new RandomAccessFile(file, "r");
      	raf.seek(start);
      	long lines = 0L;
      	for(long i=0;i<count;i++){
      		if(raf.readByte() == '\n'){
      			lines++;
      		}
      	}
      	raf.close();
      	return lines;
      }
    	
      public Long call() throws Exception {
      	return Long.valueOf(read(file, start, count));
      }
    

    }

    private static long calculate(File file, long size, int threads) throws Exception{ ExecutorService es = Executors.newFixedThreadPool(threads); CompletionService cs = new ExecutorCompletionService(es);

      long count = size/threads;
    	
      for(int i=0;i<threads;i++){
      	long start = count*i;
      	cs.submit(new FilePartCallable(file, start, count));
      }
    	
      long start = count*threads;
      long restCount = size - start;
      cs.submit(new FilePartCallable(file, start, restCount));
    	
      long lines = 0L;
      for(int i=0;i<threads+1;i++){
      	lines += cs.take().get();
      }
    	
      es.shutdown();
      return lines + 1;
    

    } } [/code] [/quote]

    这个实现不错,不过呢,太浪费了,N个处理器只有N个线程,呵呵![/quote] 单个文件的话,分片,然后多线程统计每片。求和。

    多个文件的话,排队。[/quote]

    多个文件一起来也没有关系的,会达到最终一致的,前提是原子计数和能够开启那么多的FD。[/quote] 没问题,有个pool,要排队。 如果多个pool,context切换要消耗掉一部分资源。

    这部分工作交给线程池和它内置的队列来完成就可以了,按照CPU计数是因为这种Filter字节是很耗CPU的,基本上不是任务越多越好,另外也可以节约FD。

  20. #41 楼 · javeaye · 2010-12-13 23:03

    mercyblitz writes:

    [quote=javeaye][quote=mercyblitz][quote=yangyi]1 获取文件字节数 M 2 设定指针数量 N,使得 M > N 3 根据随机位置,指向文件的不同位置,按照M/N的长度遍历,当遇到'\n'时,换行计数+1 4 注意最后的M%N部分也要进行检查 [code=java] import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;

    public class LineCounter { public static void main(String[] args) throws Exception{ File file = new File(args[0]); int threads = Runtime.getRuntime().availableProcessors(); long size = file.length(); System.out.println(calculate(file, size, threads)); }

    private static class FilePartCallable implements Callable{ private File file; private long start; private long count;

      public FilePartCallable(File file, long start, long count){
      	this.file = file;
      	this.start = start;
      	this.count = count;
      }
    	
      private long read(File file, long start, long count) throws IOException{
      	RandomAccessFile raf = new RandomAccessFile(file, "r");
      	raf.seek(start);
      	long lines = 0L;
      	for(long i=0;i<count;i++){
      		if(raf.readByte() == '\n'){
      			lines++;
      		}
      	}
      	raf.close();
      	return lines;
      }
    	
      public Long call() throws Exception {
      	return Long.valueOf(read(file, start, count));
      }
    

    }

    private static long calculate(File file, long size, int threads) throws Exception{ ExecutorService es = Executors.newFixedThreadPool(threads); CompletionService cs = new ExecutorCompletionService(es);

      long count = size/threads;
    	
      for(int i=0;i<threads;i++){
      	long start = count*i;
      	cs.submit(new FilePartCallable(file, start, count));
      }
    	
      long start = count*threads;
      long restCount = size - start;
      cs.submit(new FilePartCallable(file, start, restCount));
    	
      long lines = 0L;
      for(int i=0;i<threads+1;i++){
      	lines += cs.take().get();
      }
    	
      es.shutdown();
      return lines + 1;
    

    } } [/code] [/quote]

    这个实现不错,不过呢,太浪费了,N个处理器只有N个线程,呵呵![/quote] 单个文件的话,分片,然后多线程统计每片。求和。

    多个文件的话,排队。[/quote]

    多个文件一起来也没有关系的,会达到最终一致的,前提是原子计数和能够开启那么多的FD。

    没问题,有个pool,要排队。 如果多个pool,context切换要消耗掉一部分资源。

评论功能维护中,当前仅展示历史评论。