2011-08-03 41 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