我正在尝试在打包的 jar 之外设置一个 java .properties 文件。这是我加载它的代码:
public static final String FILENAME = "test.properties";
public static void load() throws IOException {
    FileInputStream fis = null;
    try {
        props = new Properties();
        fis = new FileInputStream(FILENAME);
        props.load(fis);
        System.out.println("Properties successfully loaded: "+props);
        validateProperties();
    } catch (FileNotFoundException e) {
        System.err.println("Properties file not found.  Creating...");
        new File(FILENAME).createNewFile();
                    //fill with default properties
        System.out.println("Properties file successfully created");
    } finally {
        if (fis != null) try {fis.close();} catch(Exception e) {}
    }
}
不幸的是,当我运行它时,我得到以下输出:
Properties successfully loaded: {}
这是test.properties:
#no comment
#Sun Jun 23 19:21:45 CDT 2013
port=55142
handSize=10
maxPlayers=8
timeout=1500
我已经通过手动读取和打印确认 FileInputStream 正在从正确的文件中读取。那么为什么我的属性没有加载呢?
编辑:这是一些直接加载属性文件内容的代码:
public static void test() throws IOException {
    FileInputStream fis = new FileInputStream(FILENAME);
    byte[] b = new byte[fis.available()];
    fis.read(b);
    String text = new String(b);
    System.out.println(text);
}
它输出:
#no comment
#Sun Jun 23 19:21:45 CDT 2013
port=55142
handSize=10
maxPlayers=8
timeout=500
所以 FIS 必须从正确的文件中读取。
编辑2:好的,所以我不知道问题出在哪里,但是我重新启动了eclipse,现在它可以工作了。非常抱歉浪费了您的时间。