如何在 webapp 中读取文件而不将其放入 Tomcat 的 /bin 文件夹中



我正试图使用文件描述符从doGet方法上的Tomcat容器中读取一个文件。该程序在执行时会在tomcat bin文件夹下查找"sample.txt"。我不希望我的资源文件成为Tomcat bin的一部分。如何以更好的方法读取文件,这使我在定义资源目录时具有灵活性。我还试图从部署为Tomcat中的助手类的POJO中读取该文件。我还可以在tomcat中配置类路径来查找不同目录中的文件吗?任何指点都会有很大帮助。

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.20binsample.txt

确实应该避免使用具有相对路径的new File()new FileInputStream()。有关背景信息,请参阅getResourceAsStream()与FileInputStream。

只需使用像这样的绝对路径

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

或者将给定路径添加到类路径中作为/conf/catalina.propetiesshared.loader属性

shared.loader = /absolute/path/to

这样您就可以从类路径中获得它,如下所示

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("sample.txt");
// ...

最新更新