1

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

    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 异常。

4

4 回答 4

1

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

InputStream fileStream = new FileInputStream(configPropertiesFile);
currConfigProperties.load(fileStream);

另外,将您的属性文件路径更改为src/com/abc/applet/Configuration.properties

您也可以使用它从类路径中加载它:-

currConfigProperties.load(this.getClass().getResourceAsStream(configPropertiesFile));
于 2013-03-19T11:27:23.390 回答
1

如果您的属性文件与您的班级位于同一位置:

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*/}

您也可以将 pass 传递给您的属性文件,-DmyPropertiesFile=./../../properties.properties然后获取它System.getProperty("myPropertiesFile")

于 2013-03-19T11:34:13.520 回答
0

从 OP 的评论加载来自类路径。所以需要用到ClassLoader,

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

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

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

于 2013-03-19T11:30:11.003 回答
0

你也可以试试这个。

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是您实现上述方法的类。

于 2019-03-19T03:29:24.290 回答