简体   繁体   中英

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. 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

//according to this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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