如何读取逗号分隔的文件
how to read a file thats comma‐delimited
我正在尝试从包含字符串列表的文件中读取。文件中有三行,我试图在文件中查看时打印它们,但输出仅打印第一行。 'woman' 不应打印。 'man'
也不应该
public void readFile(String fileName) {
String gender;
String width;
String height;
String name;
String x;
String y;
try {
scanIn = new Scanner (new File (fileName));
this.scanIn.useDelimiter(", ");
} catch (FileNotFoundException | NumberFormatException exception) {
exception.getMessage();
}
while(this.scanIn.hasNext()){
gender = scanIn.next();
if(gender.equals("woman")){
width = scanIn.next();
height = scanIn.next();
x = scanIn.next();
y = scanIn.next();
name = scanIn.next();
System.out.printf("%s %s %s %s %s", width,height,x,y,name);
}
if(gender.equals("man")){
width = scanIn.next();
height = scanIn.next();
x = scanIn.next();
y = scanIn.next();
name = scanIn.next();
System.out.printf("%s %s %s %s %s", width,height,x,y,name);
}
}
}
文件看起来像
man, 20, 15, 55, 90, phil
woman, 30, 10, 5, 80, Sam
man, 320, 170, 10, 90, olie
输出应该是
20, 15, 55, 90, phil
30, 10, 5, 80, Sam
320, 170, 10, 90, olie
相反,输出给了我
20, 15, 55, 90, phil
woman
错误是因为当你使用分隔符为", "
时,扫描器遇到换行不会停止。
因此,当它读取第一行时,它将读取 phil\nwomen
作为单个标记。所以你的循环会搞砸。
要修复,您可以告诉它在 ", |\n"
上定界,这也会在换行符上定界。
scanIn.useDelimiter(", |\n");
注意:您可能还想在 printf()
语句的末尾添加一个 换行符,否则您将在一行中获取整个输出。
我正在尝试从包含字符串列表的文件中读取。文件中有三行,我试图在文件中查看时打印它们,但输出仅打印第一行。 'woman' 不应打印。 'man'
也不应该 public void readFile(String fileName) {
String gender;
String width;
String height;
String name;
String x;
String y;
try {
scanIn = new Scanner (new File (fileName));
this.scanIn.useDelimiter(", ");
} catch (FileNotFoundException | NumberFormatException exception) {
exception.getMessage();
}
while(this.scanIn.hasNext()){
gender = scanIn.next();
if(gender.equals("woman")){
width = scanIn.next();
height = scanIn.next();
x = scanIn.next();
y = scanIn.next();
name = scanIn.next();
System.out.printf("%s %s %s %s %s", width,height,x,y,name);
}
if(gender.equals("man")){
width = scanIn.next();
height = scanIn.next();
x = scanIn.next();
y = scanIn.next();
name = scanIn.next();
System.out.printf("%s %s %s %s %s", width,height,x,y,name);
}
}
}
文件看起来像
man, 20, 15, 55, 90, phil
woman, 30, 10, 5, 80, Sam
man, 320, 170, 10, 90, olie
输出应该是
20, 15, 55, 90, phil
30, 10, 5, 80, Sam
320, 170, 10, 90, olie
相反,输出给了我
20, 15, 55, 90, phil
woman
错误是因为当你使用分隔符为", "
时,扫描器遇到换行不会停止。
因此,当它读取第一行时,它将读取 phil\nwomen
作为单个标记。所以你的循环会搞砸。
要修复,您可以告诉它在 ", |\n"
上定界,这也会在换行符上定界。
scanIn.useDelimiter(", |\n");
注意:您可能还想在 printf()
语句的末尾添加一个 换行符,否则您将在一行中获取整个输出。