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

プロパティファイルがクラスと同じ場所にある場合:

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")

于 2013-03-19T11:34:13.520 に答える
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 に答える
0

OPのコメントロードはクラスパスからです。そのため、ClassLoader を使用する必要があります。

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

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

最初のメソッドはインスタンス コンテキストにある必要があり、2 番目のメソッドは静的コンテキストから機能します。

于 2013-03-19T11:30:11.003 に答える