简体   繁体   English

从文件读取浮点数

[英]Read float numbers from file

How to read float numbers from file? 如何从文件中读取浮点数?

  0.00000E+00  2.12863E-01
  1.00000E-02  2.16248E-01
  2.00000E-02  2.19634E-01

in the file 2 spaces before the first column of numbers and between numbers. 在文件第一列之前和数字之间的2个空格中。 I have errors instantly: 我立即有错误:

s = new Scanner(new File("P0"));
while (s.hasNext()) {
    float x = s.nextFloat();
    float y = s.nextFloat();

    System.out.println("x = " + x + ", y = " + y);
}
  1. Read file line by line. 逐行读取文件。
  2. Split each line into words based on spaces. 根据空格将每行分割成多个单词。
  3. Convert each word into float. 将每个单词转换为浮点数。

Here is the code: 这是代码:

    BufferedReader reader = null;

    try {
        // use buffered reader to read line by line
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(
                "<FULL_FILE_PATH>"))));

        float x, y;
        String line = null;
        String[] numbers = null;
        // read line by line till end of file
        while ((line = reader.readLine()) != null) {
            // split each line based on regular expression having
            // "any digit followed by one or more spaces".

            numbers = line.split("\\d\\s+");

            x = Float.valueOf(numbers[0].trim());
            y = Float.valueOf(numbers[1].trim());

            System.out.println("x:" + x + " y:" + y);
        }
    } catch (IOException e) {
        System.err.println("Exception:" + e.toString());
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                System.err.println("Exception:" + e.toString());
            }
        }
    }

So, I understand my mistake. 所以,我理解我的错误。 I need to use 我需要用

s.useLocale(Locale.US);

because that Scanner interpets "." 因为该扫描程序会干扰“。” as decimal separator, in my locale (default) it is ",". 作为小数点分隔符,在我的语言环境(默认)中为“,”。 Also note that both 1.1 and 3 (integer) are recognized by nextDouble 另请注意,nextDouble可以识别1.1和3(整数)

//according to this link //根据此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM