从文件中阅读不同的数据类型

问题描述 投票:0回答:2
我必须从还存在空间和逗号的每行的文件中读取。目前,我正在使用scanner.nextline()阅读,我想知道如何解析我需要的两个双打的字符串。 我正在使用Java,但不允许使用预先构建的第三方库。 我也尝试了DatainputStream和BufferedReader。

<double>, <double>
非常慢,所以最好使用

Scanner.nextLine()

。 然后,您可以使用

BufferedReader

indexOf()
java file parsing
2个回答
0
投票

substring()

您要寻找的是拆分字符串

try (BufferedReader in = Files.newBufferedReader(filePath)) {
    for (String line; (line = in.readLine()) != null; ) {
        int idx = line.indexOf(", ");
        if (idx == -1)
            throw new IllegalArgumentException("Invalid line: " + line);
        double d1, d2;
        try {
            d1 = Double.parseDouble(line.substring(0, idx));
            d2 = Double.parseDouble(line.substring(idx + 2));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid line: " + line, e);
        }
        // code using d1 and d2 here
    }
}
然后将结果解析为double

String string = "4.0,3.2"; String[] results = string.split(","); String firstDouble = results[0]; String secondDouble = results[1];
    

0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.