Question

In trying to resolve Facebook's Puzzle "Hoppity Hop", http://www.facebook.com/careers/puzzles.php?puzzle_id=7, I'm reading one integer only from a file. I'm wondering if this is the most efficient mechanism to do this?

private static int readSoleInteger(String path) throws IOException {
    BufferedReader buffer = null;
    int integer = 0;

    try {
        String integerAsString = null;

        buffer = new BufferedReader(new FileReader(path));

        // Read the first line only.
        integerAsString = buffer.readLine();

        // Remove any surplus whitespace.
        integerAsString = integerAsString.trim();

        integer = Integer.parseInt(integerAsString);
    } finally {
        buffer.close();
    }

    return integer;
}

I have seen How do I create a Java string from the contents of a file?, but I don't know the efficiency of the idiom which answers that question.

Looking at my code, it seems like a lot of lines of code and Objects for a trivial problem...

Was it helpful?

Solution

The shortest method would be with a Scanner:

private static int readSoleInteger(String path) {
    Scanner s = new Scanner(new File(path));
    int ret = s.nextInt();
    s.close();
    return ret;
}

Note that Scanner swallows any IOExceptions, so that simplifies things a lot.

As for "most efficient"... well, the simple act of opening a file from the disk is likely to be the slowest part of any method you write for this. Don't worry too much about efficiency in this case.

Edit: I hadn't realized that the integer can have whitespace on either side of it. My code does not account for this currently, but it's easy to make the Scanner skip things. I've added the line

s.skip("\\s+");

to correct this.

Edit 2: Never mind, Scanner ignores whitespace when it's trying to parse numbers:

The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar:

(regexes snipped)

Whitespace is not significant in the above regular expressions.

OTHER TIPS

I would use the Scanner class:

Scanner sc = new Scanner(new File("my_file"));
int some_int = sc.nextInt();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top