2011-08-04 197 views
2

我已经在Eclipse中创建了一个动态Web项目,并且已经编写了一个简单的代码来读取属性文件。
这里是我的代码从属性文件中读取值

public class AutocompleteService { 

public static void main (String args[]) 
{ 
    Properties properties = new Properties(); 
    properties.load(new FileInputStream("autocomplete.properties")); 
    System.out.println("Test : " + properties.getProperty("test")); 
} 

当我运行此我得到的文件未发现异常。

java.io.FileNotFoundException: autocomplete.properties (The system cannot find the file specified) 

我的包结构如下

-src 
- com.serive (package) 
    - AutocompleteService.java 
    - autocomplete.properties 

两个AutocompleteService.javaautocomplete.properties都在同一个包即com.service。做我们需要别的从性能读取文件?

编号:http://www.exampledepot.com/egs/java.util/Props.html

〜Ajinkya。

回答

5

相关的信息流中获取到类:

AutocompleteService.class.getResourceAsStream("autocomplete.properties") 
+0

非常感谢:)它工作并且比其他人更简单。:) – xyz

+0

虽然应该是'getResourceAsStream'。 – Thilo

+0

@Thilo:是的,它应该是。我用'properties.load(AutocompleteService.class.getResourceAsStream(“autocomplete.properties”));' – xyz

7

,你必须从classpath加载这样的:前

ClassLoader loader = Thread.currentThread().getContextClassLoader(); 
stream = loader.getResourceAsStream(fileName); 

当你有流,你可以将它传递给properties.load()

2

你的代码是看在“当前目录”当应用程序运行时。

使用Class.getResourceAsStream()可以从类的相同位置读取。

+0

那么现在'com.service'不是我目前的目录吗? – xyz

+0

不,这取决于您如何启动应用程序,通常在Eclipse中工作时它将是您的工作区目录,您可以在“运行配置”,“参数”选项卡中对其进行控制。但是,当你独立运行应用程序时,你可能会在JAR中安装应用程序,所以你不能指望类目录是当前目录。使用getResourceAsStream(),你可以在Eclipse内部工作并独立工作。 – djna

0

使用相对路径将尝试在运行程序的当前目录打开一个文件创建的输入流。在你的情况下,当前目录是你的servlet容器的执行目录(Tomcat,Jetty等)

你想要做的是打开一个属性文件,它与你的类一起,在战争中文件。这个属性文件应该被类加载器覆盖,并且使用Class.getResourceAsStream()是合适的方式。查看链接的javadoc以了解哪种路径将作为参数提供。

2

“当前”目录是您启动服务器的地方,因此请参考相关文件,例如"config/autocomplete.properties"或任何您喜欢的地方。

最好的办法是知道是什么问题。像这样使用代码,可以帮助您调试问题:

File propertiesFile = new File("config/autocomplete.properties"); 
if (!propertiesFile.exists()) 
    throw new IllegalStateException("Could not find properties file: " + propertiesFile.getAbsolutePath()); 
properties.load(new FileInputStream(file)); 

如果爆炸,异常消息会告诉你它认为该文件,并yo'll迅速找出如何解决这个问题。