开发者

How to read or write .properties file outside JAR file

开发者 https://www.devze.com 2023-03-24 21:36 出处:网络
I \'v created a project that reads some of configuration from .properties file public class PreferenceManager {

I 'v created a project that reads some of configuration from .properties file

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 = Cl开发者_C百科assLoader.getSystemResource("preferences.properties").toURI();
        File f = new File(uri);
        properties.store(new  FileOutputStream(f), null);
    }
}

and every thing is ok . now I need to create a JAR file. I need to know how to make this JAR file read this properties file from the folder that contains it, because when the properties file is inside the JAR I can read it but I can write on it (Exception : URI is not hirarchal)

so I need ur Help please.

Thanks


Simply store the file in the user's home directory, which is always available, be it a Windows or Linux/Mac machine:

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

Next time, when the application starts you want to load them from user's home directory, of course, if the Properties file exists there.
Compare https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/System.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号