梦幻之旅

DEBUG - 天道酬勤

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  671 随笔 :: 6 文章 :: 256 评论 :: 0 Trackbacks
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.util.Calendar;

public class TestRowCount {
    
public static void main(String[] args) {
        
long datestart = Calendar.getInstance().getTimeInMillis();
        
int count = getFileLineCounts("XXX");
        System.out.println(count);
        
long dateend = Calendar.getInstance().getTimeInMillis();
        System.out.println((dateend 
- datestart) / 1000);
    }


    
public static int getFileLineCount(String filename) {
        
int cnt = 0;
        LineNumberReader reader 
= null;
        
try {
            reader 
= new LineNumberReader(new FileReader(filename));
            @SuppressWarnings(
"unused")
            String lineRead 
= "";
            
while ((lineRead = reader.readLine()) != null{
            }

            cnt 
= reader.getLineNumber();
        }
 catch (Exception ex) {
            cnt 
= -1;
            ex.printStackTrace();
        }
 finally {
            
try {
                reader.close();
            }
 catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        
return cnt;
    }


    
public static int getFileLineCounts(String filename) {
        
int cnt = 0;
        InputStream is 
= null;
        
try {
            is 
= new BufferedInputStream(new FileInputStream(filename));
            
byte[] c = new byte[1024];
            
int readChars = 0;
            
while ((readChars = is.read(c)) != -1{
                
for (int i = 0; i < readChars; ++i) {
                    
if (c[i] == '\n'{
                        
++cnt;
                    }

                }

            }

        }
 catch (Exception ex) {
            cnt 
= -1;
            ex.printStackTrace();
        }
 finally {
            
try {
                is.close();
            }
 catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        
return cnt;
    }

}
总结:
每行的字符较多时, 使用第一个方法效率较高
每行的字符较少时, 使用第二个方法效率较高
posted on 2012-12-06 13:39 HUIKK 阅读(2824) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: