【问题标题】:java.io.FileNotFoundException in Java code [duplicate]Java代码中的java.io.FileNotFoundException [重复]
【发布时间】:2014-08-18 19:18:31
【问题描述】:

我正在使用此代码来读取 Linux SWAP 空间:

public void getSwap() throws FileNotFoundException, IOException
    {
        Pattern pattern = Pattern.compile("([\\/A-Za-z0-9]+)[\\s]+([a-z]+)[\\s]+([0-9]+)[\\s]+([0-9]+)[\\s]+([\\-0-9]+).*");
        BufferedReader reader = new BufferedReader(new FileReader("/proc/swaps"));
        String s = reader.readLine();
        while (s != null)
        {
            Matcher matcher = pattern.matcher(s);
            if (matcher.matches())
            {
                System.out.println(s);
                System.out.println(matcher.group(3));
                System.out.println(matcher.group(4));
            }
            s = reader.readLine();
        }
        reader.close();
    }

我想修改代码以在没有文件 /proc/swaps 时返回 null。我不想在文件丢失时中断代码。

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以非常轻松地创建一个文件对象,并在创建缓冲读取器之前使用 .exists() 方法检查它的存在(以及它的 isDirectory() 方法以确保它不是目录)。

    然后,如果它不存在,您可以采取任何您想要的操作。

    响应您对代码的请求:我没有尝试编译它,但它应该像这样工作:

    File file = new File("/proc/swaps");
    if (!file.exists()) {
        System.err.println("/proc/swaps did not exist!");
        return null;
    }
    else if (file.isDirectory()) {
        System.err.println("/proc/swaps is a directory, not a file.");
        return null;
    }
    

    您还应该将您的函数包装在try { } catch() {} 中,并使用注释处理异常,因为您事先检查了存在,所以它不会发生。这样您就不必声明该函数会引发已检查的异常。

    【讨论】:

    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多