【发布时间】:2014-04-30 00:00:28
【问题描述】:
我在一个文件中有几个字符串,我应该停止并从这些字符串中读取值。例如:
This is the first line
#1 stop = 300
This is the third line
This is the 4th line
#2 stop = 400
This is the 6th line
我需要停在 #1 并从那里提取值 300。然后我必须停在 #2 并提取 400,依此类推。
我对 Java 非常陌生,无法弄清楚我的代码有什么问题。 (我还没有提取值):
public static void main(String[] args) throws IOException {
//read
File fromFile = new File("in.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(fromFile));
String line;
String firstHandler="";
while ((line = bufferedReader.readLine()) != null) {
bufferedReader.readLine();
if (firstHandler.startsWith("#1")){
System.out.println(firstHandler);
String[] parts = firstHandler.split("=");
System.out.println(Arrays.toString(parts));
}
break;
}
System.out.println(line);
bufferedReader.close();
}
}
此时它只打印第一行,这根本不是我需要的。谁能向我解释这应该如何以正确的方式完成?
【问题讨论】:
-
您需要进一步概括您的模式。您需要能够在 # 之后查找任何数字,而不是只查找 #1
-
' if (firstHandler.startsWith("#1")){ ' 看起来不适合您的目的,而是使用分隔符“#”,因此您的代码应如下所示 ' if (firstHandler.startsWith(" #")){ '
-
打开文件时没有指定编码
标签: java parsing text bufferedreader