加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 只能从文件中读取一个整数的最有效的习惯用法?

发布时间:2020-12-15 04:50:55 所属栏目:Java 来源:网络整理
导读:在尝试解决Facebook的Puzzle“Hoppity Hop”,http://www.facebook.com/careers/puzzles.php?puzzle_id=7时,我只从一个文件中读取一个整数.我想知道这是否是最有效的机制呢? private static int readSoleInteger(String path) throws IOException { Buffered
在尝试解决Facebook的Puzzle“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,因此简化了很多事情.

至于“最有效”……好吧,从磁盘打开文件的简单行为可能是你为此编写的任何方法中最慢的部分.在这种情况下,不要过分担心效率问题.

编辑:我没有意识到整数可以在它的两边都有空格.我的代码目前没有考虑到这一点,但是很容易制作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)

????在上述正则表达式中,空格并不重要.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读