我想从java中的文本文件中逐行读取,一行包含4个字段,但一个字段可以包含多个单词,For Ex。: 我有这一行:屏幕 商业 产品问题
如何将我的这三行字段存储到java中的3个String变量?
<root>
<level1>
<level2>
<level3>
<item>abc</item>
</level3>
</level2>
</level1>
</root>
答案 0 :(得分:0)
这会分割输入。如果从标准输入读取,请使用System.in而不是inputStream:
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = in.readLine()) != null) {
String[] split = line.split(" ", 3);
String var1 = split[0]; String var2 = split[1]; String var3 = split[2];
// do whatever is needed...
}
答案 1 :(得分:0)
理想情况下,您需要使用某些特定字符来指示字段之间的中断。例如,Screen|Commercial|Problem with product
。然后,您可以编写将整行读取为输入的代码,然后将其划分为子字符串。例如:
File yourFile = new File(/*file path goes here*/);
Scanner sc = new Scanner(yourFile);
String input;
String var1;
String var2;
String var3;
int breakIndex;
while (sc.hasNextLine()) {
input = sc.nextLine();
breakIndex = input.indexOf("|");
var1 = input.substring(0, breakIndex);
input = input.substring(breakIndex+1);
breakIndex = input.indexOf("|");
var2 = input.substring(0, breakIndex);
var3 = input.substring(breakIndex+1);
// do whatever it is you plan to do with those variables here
}