2016-02-05 97 views
-1

我創建了屬性文件,如config.properties。現在我想知道如何從屬性文件java中讀取參數值的過程。如何從文件夾外讀取屬性文件如果我將屬性文件聲明爲config.properties

在eclipse中使用jdk1.7。

+0

[http://www.java2s.com/Tutorial/Java/0220__I18N/AnInternationalizedSwingApplication.htm]看看這個網址 –

+4

請檢查[這裏](http://crunchify.com/java-properties-文件如何閱讀-CONFIG-屬性值合的java /)。可能重複[this](http://stackoverflow.com/questions/1318347/how-to-use-java-property-files) – Rao

+0

記事本已經徹底蹲下做這件事。 – EJP

回答

1

請參閱下面的代碼來閱讀config.properties文件。屬性文件可以是文件系統中的任何地方。您必須提供屬性文件的正確絕對路徑。

import java.io.*; 
import java.util.Properties; 

class ConfigReader 
{ 
    public static void main(String args[]) 
    { 
     try 
     { 
      InputStream inputstream; 
      Properties prop = new Properties(); 
      inputstream = new FileInputStream("pathtofile\\config.properties"); 
      if(inputstream!=null) 
      { 
       prop.load(inputstream); 
       String property1 = prop.getProperty("property1"); 
       String property2 = prop.getProperty("property2"); 
       System.out.println(property1+"\n"+property2); 
      } 
      else 
      { 
       System.out.println("File not found"); 
      } 

     } 
     catch(Exception e) 
     { 
      System.out.println("Error"); 
     } 

    } 


} 
+0

屬性通常放在classpath的某個地方,所以你可以使用MyClass.class.getClassLoader()。getResourceAsStream(filename); –