【问题标题】:Fastest way to read a file line by line with 2 sets of Strings on each line?逐行读取文件的最快方法,每行有 2 组字符串?
【发布时间】:2011-06-29 11:37:47
【问题描述】:

我可以逐行读取的最快方法是什么,每行包含两个字符串。 一个示例输入文件是:

Fastest, Way
To, Read
One, File
Line, By Line
.... can be a large file

即使字符串之间有空格,我也需要每行上总是有两组字符串,例如“按行”

目前我正在使用

FileReader a = new FileReader(file);
            BufferedReader br = new BufferedReader(a);
            String line;
            line = br.readLine();

            long b = System.currentTimeMillis();
            while(line != null){

这是否足够有效,或者是否有更有效的方式使用标准 JAVA API(请不要使用外部库)任何帮助表示感谢!谢谢!

【问题讨论】:

  • 任何类型的缓冲读取都可能比您从中读取文件的驱动器的寻道时间快得多。

标签: java bufferedreader filereader


【解决方案1】:

这取决于您所说的“高效”是什么意思。从性能的角度来看是可以的。如果您询问代码样式和大小,我个人几乎会做一些小的修正:

        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while((line = br.readLine()) != null) {
             // do something with line.
        }

对于从 STDIN 读取,Java 6 为您提供了另一种方式。使用类 Console 及其方法

readLine()readLine(fmt, Object... args)

【讨论】:

    【解决方案2】:
    import java.util.*;
    import java.io.*;
    public class Netik {
        /* File text is
         * this, is
         * a, test,
         * of, the
         * scanner, I
         * wrote, for
         * Netik, on
         * Stack, Overflow
         */
        public static void main(String[] args) throws Exception {
            Scanner sc = new Scanner(new File("test.txt"));
            sc.useDelimiter("(\\s|,)"); // this means whitespace or comma
            while(sc.hasNext()) {
                String next = sc.next();
                if(next.length() > 0)
                    System.out.println(next);
            }
        }
    }
    

    结果:

    C:\Documents and Settings\glowcoder\My Documents>java Netik
    this
    is
    a
    test
    of
    the
    scanner
    I
    wrote
    for
    Netik
    on
    Stack
    Overflow
    
    C:\Documents and Settings\glowcoder\My Documents>
    

    【讨论】:

      【解决方案3】:

      如果你想分开两组字符串,你可以这样做:

      BufferedReader in = new BufferedReader(new FileReader(file));
      String str;
      while ((str = in.readLine()) != null) {
          String[] strArr = str.split(",");
          System.out.println(strArr[0] + " " + strArr[1]);
      }
      in.close();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        • 2018-07-10
        • 2021-12-08
        • 1970-01-01
        • 2019-05-11
        • 2011-08-13
        • 2011-12-23
        相关资源
        最近更新 更多