>我有一个包含以下内容的test.txt
文件:
A,B,1,0.5
C,D,2,1.5
我有这段代码可以读取其内容并打印到控制台:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(Paths.get("test.txt"));
input.useDelimiter("\,");
while (input.hasNext()) {
System.out.printf("%s %s %d %f",
input.next(),
input.next(),
input.nextInt(),
input.nextDouble());
input.next();
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (input != null) {
input.close();
}
}
}
}
它给出了一个InputMismatchException
错误。
虽然如果文件只包含
A,B,1,0.5
它工作正常。我怀疑这是因为nextDouble()
留下了一个尾随的新行字符并尝试添加input.next()
,但是错误仍然存在。
编辑:
我知道String line = scanner.nextLine()
和String[] data = line.split(",")
的做法。但是我想了解这里出了什么问题。我不想为此使用库。
不要使用单个扫描仪来完成整个过程。分而治之:相反,使用一个扫描器读取文件的每一行,并使用基于每一行(或String#split(...)
(的第二行扫描器来解析每一行。
Scanner input = null;
try {
input = new Scanner(Paths.get("test.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split("\s*,\s*");
// or create a Scanner based on the line here and close when done
// handle tokens here
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (input != null) {
input.close();
}
}
或者更好的是,使用 CSV 解析库。
若要也接受换行符作为分隔符,请使用模式,|R
。
try (Scanner input = new Scanner(Paths.get("test.txt")) {
input.useDelimiter(",|\R");
while (input.hasNext()) {
System.out.printf("%s %s %d %f%n", input.next(), input.next(), input.nextInt(), input.nextDouble());
}
}
或者,单独分析该行的最后一部分。
try (Scanner input = new Scanner(Paths.get("test.txt")) {
input.useDelimiter(",");
while (input.hasNext()) {
System.out.printf("%s %s %d %f%n", input.next(), input.next(), input.nextInt(),
Double.parseDouble(input.nextLine().substring(1)));
}
}