The most efficient idiom for reading a single whole from a file only?

In an attempt to solve the Facebook puzzle "Hoppity Hop", http://www.facebook.com/careers/puzzles.php?puzzle_id=7 , I read the whole from the file only. I wonder if this is the most efficient mechanism for 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 saw How to create a Java string from the contents of a file? but I don’t know the effectiveness of the idiom that answers this question.

Looking at my code, it seems that there are a lot of lines of code and objects for a trivial problem ...

+3
source share
2 answers

The shortest method will be with Scanner:

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

, Scanner IOExceptions, .

" "... , , , , . .

: , . , Scanner .

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

.

2: , Scanner :

, , :

(regexes snipped)

.

+8

Scanner:

Scanner sc = new Scanner(new File("my_file"));
int some_int = sc.nextInt();
+4

Source: https://habr.com/ru/post/1710713/


All Articles