2012-04-22 83 views
0

我想讀值從屬性文件和 當我試圖運行此程序 其給出輸出
null屬性文件返回null

import java.io.FileInputStream; 
import java.util.Properties; 
public class JavaApplication1 { 
final private static String osName = System.getProperty("os.name"); 
static final Properties configFile = new Properties() { 

    { 
     try { 
      configFile.load(new FileInputStream("config.properties")); 
     } catch (Exception e) { 
     } 
    } 
}; 
private static String DIR = osName.equals("Linux") ? configFile.getProperty("tempDirForLinux") : configFile.getProperty("tempDirForWindows"); 
public static void main(String[] args) { 
    System.out.println(DIR); 
} 
} 
+0

請問您的程序加載正確的屬性?你的物業有沒有正確的財產? – Jeffrey 2012-04-22 17:51:42

+3

正如你在上一個問題的答案中所說的那樣,這是一種非常脆弱的技術。對於初學者來說,至少在該catch塊中包含'printStackTrace'。 – 2012-04-22 17:51:54

+0

發表您的屬性文件和它的位置 – 2012-04-22 17:52:42

回答

1

這是一個有點奇怪的組成部分你的例子是你創建一個匿名的Properties類的地方,然後在初始化語句中將這些屬性加載到同一個類中。我不知道這是怎麼打算的工作(我猜沒有)

這可能是你想要什麼,而

public class JavaApplication1 { 
    final private static String osName = System.getProperty("os.name"); 
    static final Properties configFile = new Properties(); 

    static { 
     try { 
      configFile.load(new FileInputStream("config.properties")); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    }; 

    private static String DIR = osName.equals("Linux") ? configFile.getProperty("tempDirForLinux") : configFile.getProperty("tempDirForWindows"); 

    public static void main(String[] args) throws IOException { 
     System.out.println(DIR); 
    } 
} 
+0

他從[他以前的問題](http://stackoverflow.com/a/10269151/1103872)中得到了它。雖然沒有接受它(對你而言,S.A.Rahman!)。無論如何,這是合法的,它沒有例外 – 2012-04-22 18:27:09

+0

@MarkoTopolnik現在感謝你,我得到了我所需要的。我真的很抱歉我的可憐的英語,沒有向你解釋我真正需要什麼。感謝您的建議和善意的評論。 – sarsarahman 2012-04-23 00:21:16

+0

我把上面的問題代碼放到我的IDE中,它不適用於我或給出一個有點奇怪的例外。但MarkoTopolnik在其他問題中發佈的代碼看起來應該也能工作。 – 2012-04-23 07:56:26