2012-12-03 23 views
0

我想从使用文件描述符的doGet方法上的Tomcat容器中读取文件。 程序执行时会在tomcat bin文件夹下查找“sample.txt”。我不希望我的资源文件成为Tomcat bin的一部分。如何以更好的方式读取文件,这使我可以灵活地定义资源目录。我也尝试从POJO中读取部署为Tomcat助手类的文件。 我也可以在tomcat中配置classpath以查找不同目录下的文件吗? 任何指针都会有很大的帮助。如何在webapp中读取文件而不将其放置在Tomcat的/ bin文件夹中

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    PrintWriter out = response.getWriter(); 
    out.print("Sample Text"); 
    RSAPublicCertificate rsa = new RSAPublicCertificate(); 
    out.print(rsa.getCertificate()); 
    File file = new File("sample.txt"); 
    out.print(file.getAbsolutePath()); 
    FileInputStream in = new FileInputStream(file); 

} 

D:\apache-tomcat-6.0.20\bin\sample.txt 

回答

1

你确实应该避免使用​​和new FileInputStream()使用相对路径。有关背景信息,另请参阅getResourceAsStream() vs FileInputStream

只需使用绝对路径,像

File file = new File("/absolute/path/to/sample.txt"); 
// ... 

或给定的路径添加到类路径为/conf/catalina.propeties

shared.loader = /absolute/path/to 

所以shared.loader属性,你可以从classpath得到它如下

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("sample.txt"); 
// ... 
相关问题