2016-07-18 58 views
1

我正在嘗試讀取config.properties文件(位於我的項目根目錄中,包含我的pom.xml,README.md,...)。但是,我總是收到「FileNotFound」異常。我應該在哪裏找到這個文件才能使用這段代碼?Java項目中config.properties文件的位置

/src/main/java/com.example.proj.db/DatabaseManager.java

public DatabaseManager() throws IOException { 
    Properties prop = new Properties(); 
    InputStream input = null; 

    input = new FileInputStream("config.properties"); 
    prop.load(input); 
    dbUser = prop.getProperty("dbUser"); 
} 

config.properties

# Database Configuration 
dbuser=wooz 
+1

通常情況下,我會說/ src目錄/主/資源/作爲起始位置<_ < – Compass

+0

遺憾的是它並沒有從該位置工作,要麼, @羅盤。同樣的錯誤。 – Arturo

+1

嘗試'getClass()。getResourceAsStream(「config.properties」)'(結合@Compass給出的建議) – Sam

回答

2

這裏就是我通常做的:

  1. 把支柱如@Compass所述,在/ src/main/resources中包含erty文件

  2. 在pom.xml的構建部分中執行資源過濾以確保將屬性文件複製到包中。

    <build> 
        ... 
        <resources> 
         <resource> 
          <directory>src/main/resources</directory> 
          <filtering>true</filtering> 
         </resource> 
        </resources> 
        ... 
    </build> 
    
  3. 由於我使用Spring加載一個屬性文件,我簡單地寫爲文件路徑「類路徑:config.properties」。但是你可能需要求助於其他技術,如locating file in a classpath

相關問題