更新答案:
啊,好吧,你想按列的宽度分割文本。看起来您的列长度是:
6
5
5
6
8
6
4
18
9
(其余的部分)
所以阅读这些行,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#readLine
and的组合String#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
使用正则表达式定义的分隔符将字符串拆分为字符串数组。在您的情况下,分隔符看起来只是一个或多个空格。