2013-03-19 105 views
0

我不能用下面來加載屬性文件片斷加載屬性文件在java中

URL configURL = null; 
    URLConnection configURLConn = null; 
    InputStream configInputStream = null; 
    currConfigProperties = new Properties(); 
    try { 
     String configPropertiesFile = getParameter("propertiesFile"); 
     if (configPropertiesFile == null) { 
      configPropertiesFile = "com/abc/applet/Configuration.properties"; 
     } 
     System.out.println("configPropertiesFile :"+configPropertiesFile); 
     configURL = new URL(getCodeBase(), configPropertiesFile); 
     configURLConn = configURL.openConnection(); 
     configInputStream = configURLConn.getInputStream(); 
     currConfigProperties.load(configInputStream); 
    } catch (MalformedURLException e) { 
     System.out.println(
      "Creating configURL: " + e); 
    } catch (IOException e) { 
     System.out.println(
      "IOException opening configURLConn: " 
       + e); 
    } 

獲得java.io.FileNotFoundException異常。

+0

我想這將工作=> configPropertiesFile =「src/com/abc/applet/Configuration.properties」 – Juvanis 2013-03-19 11:24:33

+0

大概這是一個從遠程服務器加載的小程序?還是你想從類路徑中讀取?無論哪種方式,請嘗試'ClassLoader.getResourceAsStream'方法。 – 2013-03-19 11:25:49

+0

@ bmorris591 - classpath – happy 2013-03-19 11:26:26

回答

1

您可以載入你的屬性在Java類文件以這樣的方式 -

InputStream fileStream = new FileInputStream(configPropertiesFile); 
currConfigProperties.load(fileStream); 

另外,更改到src/com/abc/applet/Configuration.properties

你也可以用它來從classpath加載你的屬性文件的路徑: -

currConfigProperties.load(this.getClass().getResourceAsStream(configPropertiesFile)); 
0

從OP的評論加載是從類路徑。因此,需要使用ClassLoader,第一種方法需要在實例上下文中,第二種方法需要在靜態上下文中工作。

0

在情況下,當你的屬性在同一個地方文件,你的類:

Properties properties = new Properties(); 
try { 
    properties.load(getClass().getResourceAsStream("properties.properties")); 
} catch (IOException e) { /*File Not Found or something like this*/} 

我的情況下,當你的財產是你的類文件的根文件夾:

Properties properties = new Properties(); 
try { 
    properties.load(getClass().getClassLoader().getResourceAsStream("properties.properties")); 
} catch (IOException e) { /*File Not Found or something like this*/} 

你也可以通過-DmyPropertiesFile=./../../properties.properties傳遞給你的屬性文件,然後得到它System.getProperty("myPropertiesFile")