【问题标题】:java.io.FileNotFoundException - Can't read my properties filejava.io.FileNotFoundException - 无法读取我的属性文件
【发布时间】:2014-04-29 12:54:23
【问题描述】:

Eclipse/Linux - Java Web 应用程序。

我在我的项目中添加了一个名为 dao.properties 的文件。我把它放在一个包里:com.cdp.dao。我使用这个文件的类在同一个包中。 当我尝试加载它时,我有一个

java.io.FileNotFoundException 
/myproject/src/com/cdp/dao/dao.properties (No such file or directory) OR 
dao.properties (No such file or directory)

这是我的代码:

Properties prop;
FileInputStream fis;
File file = new File("/myproject/src/com/cdp/dao/dao.properties");
//File file = new File("dao.properties"); doesn't work either
try {

    prop    = new Properties();
    fis = new FileInputStream(file);
    prop.load(fis);         
    dbUrl   = prop.getProperty("dbUrl");
    user    = prop.getProperty("user");
    pwd     = prop.getProperty("pwd");
    driver  = prop.getProperty("driver");
    fis.close();
} catch (FileNotFoundException e) {         
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

【问题讨论】:

  • 只需在 File 构造函数中使用 com/cdp/dao/dao.properties..并告诉我
  • 它没有用。当我提到绝对路径名时它会起作用。猜猜我不明白构造函数例外的字符串路径。现在可以了,谢谢。

标签: eclipse filenotfoundexception fileinputstream


【解决方案1】:

使用

this.getClass().getResourceAsStream("dao.properties"); 

加载属性文件

【讨论】:

    【解决方案2】:

    From Class,路径是相对于类的包的,除非

    你包含一个前导斜杠,所以如果你不想使用当前的包,

    包括这样的斜线:

    InputStream in = this.getClass().getResourceAsStream("/dir/SomeTextFile.txt");
    

    但如果您需要使用类路径,请使用如下所示的文件名

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

    【讨论】:

    • 第二种解决方案对我来说是正确的。我认为 File 或 FileInputStream 构造函数使用相对路径。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 2012-09-30
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多