Java – the most effective idiom for reading only one integer from a file?
Trying to solve Facebook's Puzzle "happiness hop", http://www.facebook.com/careers/puzzles.php?puzzle_id=7 I only read an integer from a file I wonder if this is the most effective mechanism?
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;
}
How do I create a Java string from the contents of a file?, But I don't know the efficiency of the idiom to answer this question
Looking at my code, it seems that many lines of code and objects are a trivial problem
Solution
The shortest way is to use scanner:
private static int readSoleInteger(String path) {
Scanner s = new Scanner(new File(path));
int ret = s.nextInt();
s.close();
return ret;
}
Please note that scanner swallows any ioexceptions, thus simplifying a lot of things
As for "most effective"... Well, the simple act of opening a file from disk may be the slowest part of any method you write for this In this case, don't worry too much about efficiency
Editor: I didn't realize that an integer can have spaces on both sides of it My code doesn't take this into account at present, but it's easy to make scanner skip things I have added this line
s.skip("\\s+");
Correct this
Edit 2: it doesn't matter. Scanner ignores spaces when trying to parse numbers:
