Java config.properties文件如果不存在,如何在控制台中传递消息并继续进行下一次安装而不引发异常

Java config.properties文件如果不存在,如何在控制台中传递消息并继续进行下一次安装而不引发异常,java,Java,我需要在加载之前检查config.properties是否存在,如果不存在,只需在console system.out.println(“未找到config.properties”)抛出FileNotFoundException 如果文件不存在,是目录而不是常规文件,或者由于某些其他原因无法打开以进行读取 您可以捕获FileNotFoundException并打印软警告。例如: public static String readProperty(String property) { Pr

我需要在加载之前检查config.properties是否存在,如果不存在,只需在console system.out.println(“未找到config.properties”)

抛出
FileNotFoundException

如果文件不存在,是目录而不是常规文件,或者由于某些其他原因无法打开以进行读取

您可以捕获
FileNotFoundException
并打印软警告。例如:

public static String readProperty(String property) {
    Properties prop;
    String value = null;
    try {
        prop = new Properties();
        prop.load(new FileInputStream(new File("config.properties")));

        value = prop.getProperty(property);

        if (value == null || value.isEmpty()) {
            throw new Exception("Value not set or empty");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return value;
}
如果未设置属性或读取属性文件时发生错误,则方法
readProperty()
现在返回
null
,如果文件不存在,该方法还会打印一条消息:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class PropTest
{
        public static String readProperty(String property)
        {
                try (FileInputStream f = new FileInputStream(new File("config.properties"))) {
                        Properties prop = new Properties();
                        prop.load(f);
                        return prop.getProperty(property);

                } catch (FileNotFoundException e) {
                        System.out.println("config.properties not found");
                } catch (Exception e) {
                        e.printStackTrace();
                }

                return null;
        }

        public static void main(String[] args)
        {
                String value = readProperty("foo.bar");
                System.out.println(value);

                value = readProperty("foo.baz");
                System.out.println(value);
        }
}
该行:

$ javac PropTest.java
$ java PropTest
config.properties not found
config.properties not found
$ echo "foo.bar=Hello world" > config.properties
$ java PropTest
Hello world
null
$
使用一种称为的方法,当代码处理完文件时,它会自动关闭该文件

try (FileInputStream f = new FileInputStream(new File("config.properties"))) {