2016-05-13 74 views
0

我们试图使用fileInputStream读取servlet中的属性文件。FileInputStream在Web应用程序中不起作用

但是,我们是constanlty获取文件未找到异常。

这是一段代码,我们在使用的getResourceAsStream它工作正常使用

Properties properties = new Properties(); 
      File propertyFile = new File("config" + File.separatorChar + "abc.properties"); 
      try { 
      FileInputStream propertyFileStream = new FileInputStream(propertyFile); 
       properties.load(propertyFileStream); 
       propertyFileStream.close(); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

但是我们需要理解为什么FileInputStream不起作用。

我们已将config \ abc.properties文件放入webInf中。我们也尝试将它放在src文件夹(java classpath),webContent文件夹,WebInf \ Classes文件夹中但没有成功。

+0

不工作?你无法获得房产价值? –

+0

这是给FileNotFOundException – user123

+0

,我打电话给它的网络应用程序 – user123

回答

0

资源不是文件。他们不住在文件系统中,他们不能通过FileFileInputStream访问。您应该使用Class.getResource()

+0

但为什么我能够在独立程序中访问它? – user123

+0

同一段代码 – user123

+0

因为在独立程序中没有使用JAR文件,所以您正在从文件系统访问类。 – EJP

0

尝试使用

ResourceBundle resource = ResourceBundle.getBundle("test"); 
    String VALUE1=resource.getString("KEY1"); 
    String VALUE2=resource.getString("KEY2"); 
+0

好的。但为什么没有FileInputStream工作....至于为什么这个独立的作品,但不是在网络的情况下? – user123

0

您应使用此代码来获得对Web应用程序资源,因为该路径必须从ServletContext的采取,我想这就是你要找的内容,如果你是里面的Servlet :

InputStream is = getContext().getResourceAsStream("/WEB-INF/yourFolder/abc.properties"); 

获得的完整路径的兴趣:

String fullPath = getContext().getRealPath("/WEB-INF/yourFolder/abc.properties"); 
相关问题