我有一个像这样结构的文本文件:
class Object0 extends Object1
class Object2 extends Object3
class Object1
class Object4 extends Object1
class Object3
我想拆分每个字符串并存储它。我知道如何在每行知道字符串数量时这样做,但在这种情况下,给定行上可以有两个或四个字。
这是我知道字符串数量时分割的内容:
public static void main(String[] args) {
try {
File f = new File("test.txt");
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split(" ");
String classIdentifier = details[0];
String classNameFirst = details[1];
// String classExtends = details[2];
// String classNameSecond = details[3];
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
您可以在details
数组上循环以获取每个分割的字符串,无论它们有多少。另外,我在您的main
方法中进行了一些更改,以使其更正确(添加了一个finally子句来关闭Scanner
资源)。
public static void main(String[] args) {
Scanner sc = null;
try {
File f = new File("test.txt");
sc = new Scanner(f);
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split(" ");
for(String str: details) {
//variable str contains each value of the string split
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
sc.close();
}
}
答案 1 :(得分:0)
在每次迭代中,您都可以检查是否还有两个单词:
public static void main(String[] args) {
try {
File f = new File("test.txt");
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split(" ");
String classIdentifier = details[0];
String classNameFirst = details[1];
// this can be done because you declared there
// can be only 2 or 4 words per line
if (details.length==4) {
String classExtends = details[2];
String classNameSecond = details[3];
}
// do something useful here with extracted fields (store?)
// before they get destroyed in the next iteration
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}