Java如何逐行读取文本文件并单独获取该行的文本(长度文本)

时间:2013-08-11 08:58:47

标签: java

我有这样的文本文件。

12A   aa65 3244 5          665     fr    65  3434344344343     888dds     77786334 6h
1114  22   6FF  7    d     M6      h     o8  665466676         8Pt        543NNv   9

文件位于不同宽度的列中,例如,第一列是6个字符宽,第二列是5,第三列是5,依此类推。

我想将每一行拆分为列中的值,如第一行所示:

12A , aa65 , 3244 , 5 , , 665 , fr , 65 , 3434344344343 , 888dds , 77786334 , 6h

5 个答案:

答案 0 :(得分:4)

更新回答

啊,好吧,你想要按照列的宽度分割文本。看起来您的列长度是:

6
5
5
6
8
6
4
18
9
(the rest)

请阅读BufferedReader#readLine行,然后使用String#substring获取其中的各个部分,并可能String#trim修剪空白:

BufferedReader r = /*...get a BufferedReader for your input...*/;
String line;
String[] parts;
int[] columns = new int[]{ // The starting index of each column
    6,
    5+6,
    5+5+6,
    6+5+5+6,
    8+6+5+5+6,
    6+8+6+5+5+6,
    4+6+8+6+5+5+6,
    18+4+6+8+6+5+5+6,
    9+18+4+6+8+6+5+5+6
};
int i;
int start, end;
int linelen;

// Read each line
while ((line = r.readLine()) != null) {
    // Get its length
    linelen = line.length();

    // Get an array for the result
    parts = new string[columns.length];

    // Loop through our column starting indexes
    for (i = 0; i < columns.length; ++i ) {
        // Get the start and end indexes for this column
        start = columns[i];
        end = i < columns.length - 1 ? columns[i+1] : linelen;

        // Is the string long enough?
        if (linelen < start) {
            // No, use null
            parts[i] = null;
        }
        else {
            // Yes, grab the text
            parts[i] = line.substring(start, end > linelen ? linelen : end);

            // Note - you may want `.trim()` on the end of the above, if you
            // don't want trailing spaces (or leading spaces, but none of your
            // examples has leading spaces).
        }
    }

    // **Use the `parts` of this line.
}

您也可以考虑为parts使用类而不是数组,并将其解析逻辑放在类中。


原始回答

听起来就像您正在寻找BufferedReader#readLineString#split的组合:

BufferedReader r = /*...get a BufferedReader for your input...*/;
String line;
String[] parts;

while ((line = r.readLine()) != null) {
    parts = line.split(" +");
    // Use the `parts` array
}

readLine从输入中读取行。

split使用正则表达式定义的分隔符将字符串拆分为字符串数组。在您的情况下,分隔符看起来只是一个或多个空格。

答案 1 :(得分:4)

使用Scanner读取文件,使用subString(start,end)方法解析每个字段。

Scanner sc = new Scanner(new File("myFile"));
while (sc.hasNextLine()) {
   String aLine = sc.nextLine();
   String field1 = aLine.subString(0,6);
   String field2 = aLine.subString(6,11);
   ...
}

答案 2 :(得分:1)

您可以按空格使用readline()然后split

答案 3 :(得分:1)

你想做一个像here这样的字符串分割。

我假设您已阅读该文件,只是想将其拆分。

使用Str.split("\n")表示行,Str.split(" ")表示空格(如果需要)

答案 4 :(得分:1)

java中的几种形式的阅读器都有.ReadLine()方法。 这将从源读取输入,直到遇到换行符。

对于文件读取我通常使用BufferedReader作为FileReader的包装器,因为这对批量读取更有效。 (对于每次调用read方法,FileReaders都会从文件中读取。)

编辑添加: 如果你想要对结果进行排序,那么将数据完全读入内存然后进行排序会更加高效 ,因为随机磁盘访问速度非常慢。

将行读入列表或优先级队列,使用自定义比较器将实现您所追求的目标。