2016-06-21 85 views
1

我有一個簡單的java程序來測試在java中嘗試使用資源,我得到了File Not Found錯誤,程序和文件在同一個包中,有人可以告訴我什麼目錄沒有File資源開始嘗試使用資源Java 7

public class LoadConfigFile { 

    public static String getProperty(String propertyName) { 
     String propertyValue = null; 
     try (InputStream in = new FileInputStream("Properties.properties")) { 
      Properties prop = new Properties(); 
      prop.load(in); 

      propertyValue = prop.getProperty(propertyName); 

     } catch (IOException e) { 

      System.out.println("Error Reading Property File" + e.getMessage().toString()); 
     } 
     return propertyValue; 
    } 

} 

Properties.properties搜索

properties.one=1 
properties.two=2 
properties.three=3 
properties.four=4 
properties.five=5 

Main.java

public class Main { 

    public static void main(String[] args) { 

     String s = LoadConfigFile.getProperty("property.one"); 

     System.out.println(s); 

    } 

} 
+0

有可能你不在你認爲你的目錄工作。這行應該幫助你弄明白:System.out.println(「Active file location is:」+ new File()。getAbsolutePath()); 。只需補充一點,它會被調用,你應該對發生的事情有更好的瞭解。 – Jeutnarg

回答

3

Working directory過程,以獲取在Java中,你可以使用

System.out.println(System.getProperty("user.dir")); 
3

如果你有一個Java包中的文件,你不應該訪問的文件,但作爲資源:

InputStream in = this.getClass().getResourceAsStream("Properties.properties"); 
0

如果你看一下FileInputStream構造函數的源代碼,您會看到它反過來調用File的構造函數。

如果您查看了File的文檔,您將找到解釋路徑字符串方式的一個很好的解釋。

特別地,注意到以下片段:

的路徑名,是否抽象或字符串形式,可以是絕對 或相對的。絕對路徑名是完整的,因爲不需要其他 信息來查找它所表示的文件。相對而言,相對路徑名必須根據從其他路徑名取得的信息來解釋 。 默認情況下, java.io程序包中的類始終針對當前用戶目錄解析相對路徑名。該目錄由系統屬性 user.dir命名,並且通常是調用Java虛擬機器的目錄。