如何在JAR文件外读取或写入.properties文件

时间:2011-08-03 23:04:53

标签: java properties jar

我创建了一个项目,从.properties文件中读取一些配置

public class PreferenceManager {
    private int refreshTime;
    private String[] filters;
    Properties properties ;
    public PreferenceManager() throws FileNotFoundException, IOException
    {
        properties = new Properties();


        properties.load(ClassLoader.getSystemResourceAsStream ("preferences.properties"));

    }


    public void save() throws IOException, URISyntaxException
    {
        properties.setProperty("REFRESH_TIME", String.valueOf(refreshTime));
        String filtersStr = "";
        if(filters!= null){
            for(String str : filters)
            {
                if((str == null)||(str.isEmpty())) continue;
                filtersStr+= str.toUpperCase()+",";
            }
        }
        properties.setProperty("FILTERS", filtersStr);
        URI uri = ClassLoader.getSystemResource("preferences.properties").toURI();
        File f = new File(uri);
        properties.store(new  FileOutputStream(f), null);
    }
}

并且每件事都没问题。现在我需要创建一个JAR文件。我需要知道如何做到这一点 JAR文件从包含它的文件夹中读取此属性文件,因为当属性文件在JAR中时我可以读取它但我可以在其上写(例外:URI不是hirarchal)

所以我需要你的帮助。

由于

1 个答案:

答案 0 :(得分:7)

只需将文件存储在用户的主目录中,该目录始终可用,无论是Windows还是Linux / Mac计算机:

// Initially load properties from jar
Properties props = new Properties();
properties.load(ClassLoader.getSystemResourceAsStream ("preferences.properties"));

// .. work with properties

// Store them in user's home directory
File userHome = new File(System.getProperty("user.home"));
File propertiesFile = new File(userHome, "preferences.properties");

props.store(new FileOutputStream(propertiesFile, "Properties for MyApp");

下次,当应用程序启动时,您希望从用户的主目录加载它们,当然,如果存在属性文件。
比较https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/System.html