在尝试解决 Facebook 的难题“Hoppity Hop”时,http://www.facebook.com/careers/puzzles.php?puzzle_id=7 ,我只从文件中读取一个整数。我想知道这是否是最有效的机制?
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? , 但我不知道回答这个问题的习语的效率。
看我的代码,似乎有很多代码行和对象来解决一个微不足道的问题......
最佳答案
最短 方法是使用 Scanner
:
private static int readSoleInteger(String path) {
Scanner s = new Scanner(new File(path));
int ret = s.nextInt();
s.close();
return ret;
}
请注意,Scanner
会吞噬任何 IOExceptions
,这样可以大大简化事情。
至于“最有效”……好吧,从磁盘打开文件这个简单的 Action 可能是您为此编写的任何方法中最慢的部分。在这种情况下不要太担心效率。
编辑:我没有意识到整数的两边可以有空格。我的代码目前没有考虑到这一点,但很容易制作 Scanner
skip things .我添加了行
s.skip("\\s+");
纠正这个问题。
编辑 2:没关系,Scanner
在尝试解析数字时会忽略空格:
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)
空格在上述正则表达式中并不重要。
关于java - 仅从文件中读取一个整数的最有效习惯用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1009250/