迭代文件列表以检查内部有多少行

时间:2015-02-16 01:49:28

标签: java inputstream

我一直在尝试编写一个简单的代码,我可以浏览文件名列表,浏览每个文件名,并计算每个文件中有多少行。 但是下面的代码似乎根本不起作用(继续在eclipse中启动调试透视图)。

public class fileScanner {

public static void main(String[] args) throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    //add files
    list.add("C:\\Users\\HuiHui\\Documents\\eclipse\\test.txt");
    for (String l : list){
        fileScan(l);
    }

}

public static int fileScan(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean endsWithoutNewLine = false;
        while ((readChars = is.read(c)) != -1) {
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n')
                    ++count;
            }
            endsWithoutNewLine = (c[readChars - 1] != '\n');
        }
        if(endsWithoutNewLine) {
            ++count;
        } 
        return count;
    } finally {
        is.close();
    }
}

}

任何人都可以对此有所了解吗?

3 个答案:

答案 0 :(得分:1)

您是否有理由使用InputStream并创建BufferedInputStream而不是使用BufferedReader为您完成工作?

尝试使用filescan方法

int filescan(String filename) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(filename));
   int count=0;
   String s;
   while((s=br.nextLine()) != null) 
       count++;
   br.close();
   return count;
}

答案 1 :(得分:0)

您可以使用Scanner遍历每个文件,然后为每一行增加一个整数。

示例:

while(scanner.hasNextLine()) {
    scanner.nextLine();
    integer++;
}

答案 2 :(得分:0)

尝试LineNumberReader

public static int fileScan(String filename) throws IOException {
    File file = new File(filename);
    LineNumberReader lnr = null;
    try {
        lnr = new LineNumberReader(new FileReader(file));
        lnr.skip(file.length());//go to end of file
        return lnr.getLineNumber();
    } finally {
        if(null != lnr) {
            lnr.close();
        }
    }
}