2011-08-03 37 views
1

我“V创建了一个项目,上面写着一些从配置的.properties文件如何读或写的.properties文件以外的JAR文件

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)

所以我需要你的帮助。

感谢

+0

我遇到了同样的问题。我无法弄清楚。我玩过一个名为one-jar的项目,但它不支持非jar资源加载。最终,我崩溃了,现在我在.jar之外即时生成属性文件。 – djangofan

回答

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

+0

感谢安德烈亚斯, 它与我合作,但我不得不使用System.getProperty(“user.home”) 而不是System.getEnv。 – Jacob

+0

也谢谢你指出。此外我还想到,您可以查询由您定义的环境属性,为JDK和Maven commpare JAVA_HOME或M2设置。一些像JBoss这样的应用程序容器在容器中定义了环境变量。 –

+0

如何从jar文件所在的工作目录读取文件,而不是从主目录读取文件。 – SoulMan