使用Java找出文件中有多少非空行的最快方法是什么?

使用Java找出文件中有多少非空行的最快方法是什么?,java,Java,使用Java找出文件中有多少非空行的最快方法是什么?最简单的方法是使用扫描仪是的,我喜欢详细的代码。。。你可以把它缩短。扫描仪还可以读取文件、读取器等。。。这样你就可以把你所有的都传过去 import java.util.Scanner; public class Main { public static void main(final String[] argv) { final Scanner scanner; final int

使用Java找出文件中有多少非空行的最快方法是什么?

最简单的方法是使用扫描仪是的,我喜欢详细的代码。。。你可以把它缩短。扫描仪还可以读取文件、读取器等。。。这样你就可以把你所有的都传过去

import java.util.Scanner;


public class Main
{
    public static void main(final String[] argv)
    {
        final Scanner scanner;
        final int     lines;

        scanner = new Scanner("Hello\n\n\nEvil\n\nWorld");
        lines   = countLines(scanner);
        System.out.println("lines = "  + lines);
    }

    private static int countLines(final Scanner scanner)
    {
        int lines;

        lines = 0;

        while(scanner.hasNextLine())
        {
            final String line;

            line = scanner.nextLine();

            if(line.length() > 0)
            {
                lines++;
            }
        }

        return lines;
    }
}

最简单的方法是使用BufferedReader,并检查哪些行是空的。但是,这是一种相对缓慢的方法,因为它需要为文件中的每一行创建一个字符串对象。一种更快的方法是使用read将文件读入数组,然后遍历数组以计算换行次数

下面是两个选项的代码;第二次在我的机器上花费了大约50%的时间

public static void timeBufferedReader () throws IOException
{
    long bef = System.currentTimeMillis ();

    // The reader buffer size is the same as the array size I use in the other function
    BufferedReader reader = new BufferedReader(new FileReader("test.txt"), 1024 * 10);
    int counter = 0;
    while (reader.ready())
    {
        if (reader.readLine().length() > 0)
            counter++;
    }

    long after = System.currentTimeMillis() - bef;

    System.out.println("Time: " + after + " Result: " + counter);

}

public static void timeFileReader () throws IOException
{
    long bef = System.currentTimeMillis();

    FileReader reader = new FileReader("test.txt");
    char[] buf = new char[1024 * 10];
    boolean emptyLine = true;
    int     counter = 0;
    while (reader.ready())
    {
        int len = reader.read(buf,0,buf.length);
        for (int i = 0; i < len; i++)
        {
            if (buf[i] == '\r' || buf[i] == '\n')
            {
                if (!emptyLine)
                {
                    counter += 1;
                    emptyLine = true;
                }
            }
            else emptyLine = false;
        }
    }

    long after = System.currentTimeMillis() - bef;

    System.out.println("Time: " + after + " Result: " + counter);

}

如果它真的必须是最快的,你应该调查一下。然后,在目标平台上测试代码,看看使用NIO是否真的更好。我能够在一些代码中获得一个数量级的改进,这些代码是我在为。它涉及将数千个文件解析为更紧凑、快速加载的二进制格式。NIO对我发展缓慢的笔记本电脑有很大的帮助。

根据NIO的建议,我支持边缘系统。我在Daphna的测试代码中添加了一个NIO方法,并将其与他的两个方法进行了对比:

public static void timeNioReader () throws IOException {
    long bef = System.currentTimeMillis();

    File file = new File("/Users/stu/test.txt");
    FileChannel fc = (new FileInputStream(file)).getChannel(); 
    MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, 0, file.length());
    boolean emptyLine = true;
    int     counter = 0;

    while (buf.hasRemaining())
    {
        byte element = buf.get();

        if (element == '\r' || element == '\n') {
            if (!emptyLine) {
                counter += 1;
                emptyLine = true;
            }
        } else 
            emptyLine = false;

    }

    long after = System.currentTimeMillis() - bef;

    System.out.println("timeNioReader      Time: " + after + " Result: " + counter);

}
以下是89MB文件的预热结果:

timeBufferedReader Time: 947 Result: 747656
timeFileReader     Time: 670 Result: 747656
timeNioReader      Time: 251 Result: 747656
NIO比FileReader快2.5倍,比BufferedReader快4倍

使用6.4MB的文件,结果甚至更好,尽管预热时间要长得多

//jvm start, warming up
timeBufferedReader Time: 121 Result: 53404
timeFileReader     Time: 65 Result: 53404
timeNioReader      Time: 40 Result: 53404

//still warming up
timeBufferedReader Time: 107 Result: 53404
timeFileReader     Time: 60 Result: 53404
timeNioReader      Time: 20 Result: 53404

//ripping along
timeBufferedReader Time: 79 Result: 53404
timeFileReader     Time: 56 Result: 53404
timeNioReader      Time: 16 Result: 53404

你想怎么做就怎么做

对于落选的选民来说,既然你没有说为什么你会落选,我猜:最快有两个含义。。。执行速度最快,开发速度最快。我用最简单的开发来限定它,以防这就是所谓的最快。如果是因为其他原因,很高兴知道为什么投票会被否决。