用java加载属性文件

用java加载属性文件,java,properties,Java,Properties,我无法使用下面的代码段加载属性文件 URL configURL = null; URLConnection configURLConn = null; InputStream configInputStream = null; currConfigProperties = new Properties(); try { String configPropertiesFile = getParameter("propertiesFile");

我无法使用下面的代码段加载属性文件

    URL configURL = null;
    URLConnection configURLConn = null;
    InputStream configInputStream = null;
    currConfigProperties = new Properties();
    try {
        String configPropertiesFile = getParameter("propertiesFile");
        if (configPropertiesFile == null) {
            configPropertiesFile = "com/abc/applet/Configuration.properties";
        }
        System.out.println("configPropertiesFile :"+configPropertiesFile);
        configURL = new URL(getCodeBase(), configPropertiesFile);
        configURLConn = configURL.openConnection();
        configInputStream = configURLConn.getInputStream();
        currConfigProperties.load(configInputStream);
    } catch (MalformedURLException e) {
        System.out.println(
            "Creating configURL: " + e);
    } catch (IOException e) {
        System.out.println(
            "IOException opening configURLConn: "
                + e);
    }

正在获取java.io.FileNotFoundException异常。

您可以通过以下方式在java类中加载属性文件:-

InputStream fileStream = new FileInputStream(configPropertiesFile);
currConfigProperties.load(fileStream);
另外,将属性文件路径更改为
src/com/abc/applet/Configuration.properties

您还可以使用此命令从类路径加载它:-

currConfigProperties.load(this.getClass().getResourceAsStream(configPropertiesFile));

从OP的注释加载是从类路径。因此需要使用类加载器

public void load() {
    getClass().getResourceAsStream("my/resource");
}

public static void loadStatic() {
    Thread.currentThread().getContextClassLoader().getResourceAsStream("my/resource");
}

第一个方法需要在实例上下文中,第二个方法将在静态上下文中工作。

如果属性文件与类位于同一位置:

Properties properties = new Properties();
try {
    properties.load(getClass().getResourceAsStream("properties.properties"));
} catch (IOException e) { /*File Not Found or something like this*/}
当您的属性位于类文件的根文件夹中时,我会考虑以下情况:

Properties properties = new Properties();
try {
    properties.load(getClass().getClassLoader().getResourceAsStream("properties.properties"));
} catch (IOException e) { /*File Not Found or something like this*/}

您还可以使用
-DmyPropertiesFile=./../../properties.properties
将密码传递给属性文件,然后获取它
System.getProperty(“myPropertiesFile”)

您也可以尝试一下

public static void loadPropertiesToMemory() {
    Properties prop = new Properties();
    InputStream input = null;
    String filePathPropFile = "configuration.properties";
    try {
        input = App.class.getClassLoader().getResourceAsStream(filePathPropFile);
        prop.load(input);
    } catch (IOException ex) {
        ex.printStackTrace();
    } 
}

App
是实现上述方法的类。

我猜这将起作用=>configPropertiesFile=“src/com/abc/applet/Configuration.properties”这可能是从远程服务器加载的小程序?或者您正在尝试从类路径读取?无论哪种方法,请尝试
ClassLoader.getResourceAsStream
方法。@bmorris591-classpath