2014-01-16 46 views
3

我想我確實想要做他所做的事here如何在Eclipse Java動態Web項目中讀取屬性文件?

但是對我來說有點不同。我開始檢查文件是否存在:

File f = new File("properties.txt"); 
System.out.println(f.exists()); 

我沒有在其他職位描述,但我編譯的類在/project/build/classes所以我把我的屬性文件存在(確切的文件夾/project/WebContent/WEB-INF/classes:在我正在訪問該文件的類的包文件夾)。

但它仍然打印false。也許我做錯了,如果是這樣,請告訴我。

+0

可能重複(http://stackoverflow.com/questions/8285595/reading-properties-file-in-java) – vzamanillo

回答

2

如果您的文件位於類路徑或類文件夾中,而不是從類路徑中獲取路徑。不要使用java.io.File的相對路徑,它取決於你在JAVA代碼中沒有控制的當前工作目錄。

你可以嘗試這樣的:

URL url = getClass().getClassLoader().getResource("properties.txt"); 
File f = new File(url.getPath()); 
System.out.println(f.exists()); 

如果你的文件properties.txt是給相對路徑getResource(...)功能的包內。例如getResource("properties\\properties.txt")

+0

我把文件在'/ project/build/classes'下,我嘗試了你的建議。我在這行'File f = new File(url.getPath());'中得到'NullPointerException'。在那之後,我嘗試了'System.out.println(url.getPath());'並且得到了這個異常,所以看起來這個類不能訪問這個文件。它放錯了位置?或者我必須像classpath一樣改變? – elementzero23

+0

'getResouce(...)'參數中給出的路徑是什麼?確保文件在您提供的路徑上。 –

+0

System.out.println(f.getAbsolutePath()); –

1

執行此操作的代碼非常簡單。讓我們考慮一下,你有一個名爲SampleApp.war戰爭文件,其中有一個屬性文件名爲myApp.properties在它的根:

SampleApp.war 

| 

    |-------- myApp.properties 

    | 

    |-------- WEB-INF 

       | 
       |---- classes 
         | 
         |----- org 
           |------ myApp 
              |------- MyPropertiesReader.class 

讓我們假設你想讀一個名爲abc存在於性能屬性文件:

myApp.properties

abc = someValue; 
xyz = someOtherValue; 

讓我們考慮存在於你的應用程序的類org.myApp.MyPropertiesReader想讀的財產。下面是相同的代碼:

package org.myapp; 

import java.io.IOException; 
import java.io.InputStream; 
import java.util.Properties; 

/** 
* Simple class meant to read a properties file 
* 
* @author Sudarsan Padhy 
* 
*/ 
public class MyPropertiesReader { 

    /** 
    * Default Constructor 
    * 
    */ 
    public MyPropertiesReader() { 

    } 

    /** 
    * Some Method 
    * 
    * @throws IOException 
    * 
    */ 
    public void doSomeOperation() throws IOException { 
     // Get the inputStream 
     InputStream inputStream = this.getClass().getClassLoader() 
       .getResourceAsStream("myApp.properties"); 

     Properties properties = new Properties(); 

     System.out.println("InputStream is: " + inputStream); 

     // load the inputStream using the Properties 
     properties.load(inputStream); 
     // get the value of the property 
     String propValue = properties.getProperty("abc"); 

     System.out.println("Property value is: " + propValue); 
    } 

} 
[Java中讀取屬性文件]中
相關問題