2016-06-21 84 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虚拟机器的目录。