javafileparsing

Read in different data types from file


ONLY NEED EXPLANATION NO CODE NEEDED!

I have to read in from a file where the format is <double>, <double> per line where the space and comma are also present. Currently I am reading in with a scanner.nextLine() and I want to know how to parse the String I get for the two doubles I need.

I am using java but not allowed to use pre-built third party libraries.

I have tried DatainputStream and BufferedReader also.


Solution

  • Scanner.nextLine() is very slow, so it's better to use BufferedReader.

    You can then use indexOf() and 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
        }
    }