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

Jac*_*cob 1 java jar properties

我创建了一个项目,从.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

一切都很好.现在我需要创建一个JAR文件.我需要知道如何让这个JAR文件从包含它的文件夹中读取这个属性文件,因为当属性文件在JAR中时我可以读它但我可以在上面写(例外:URI不是hirarchal)

所以我需要你的帮助.

谢谢

And*_*ger 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");
Run Code Online (Sandbox Code Playgroud)

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