属性文件的相对路径

5

我正在使用一个属性文件:

try 
{
    properties.load(new FileInputStream("filename.properties"));
} 
catch (IOException e) 
{
}

我应该把filename.properties放在哪里?我不想指定绝对路径,因为这段代码需要在不同的平台上工作。我试着把它放在与类相同的目录下,但是它不起作用。(如果这是个愚蠢的问题,我很抱歉)

也许我可以以某种方式获取当前类所在的路径?

2个回答

4

确保你的属性文件对已编译的(.class)文件可用,并通过以下方式获取它

getClass().getResource("filename.properties") // you get an URL, then openStream it

或者
getClass().getResourceAsStream("filename.properties") // you get an InputStream

例子:

import java.net.URL;
public class SampleLoad {
    public static void main(String[] args) {
        final URL resource = SampleLoad.class.getResource("SampleLoad.class");
        System.out.println(resource);
    }
}

此主程序在运行时检索自己的编译版本:

file:/C:/_projects/toolbox/target/classes/org/game/toolbox/SampleLoad.class


好的,它可以工作,但我必须从路径中删除“file:/”,所以我必须在我的代码中用以下内容替换“new FileInputStream(filename.properties)”: FileInputStream(resource.toString().substring("file:/".length(),resource.toString().length()))); - de3
1
@de3,使用@Guillaume的第二种形式getResourceAsStream(*)。即使您将类打包到jar文件中,它仍将继续工作。 - Paul Webster

0
你可以使用以下代码: String userDir = System.getProperty("user.dir");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接