简体   繁体   中英

How to read a file in webapp without placing it in Tomcat's /bin folder

I am trying to read a file from Tomcat container on doGet method using File descriptor. The program when executed looks for "sample.txt" under tomcat bin folder. I dont want my resource file to be part of Tomcat bin. How do i read the file in a better approach which gives me flexibility in defining my resource directory. I am also trying to read the file from POJO deployed as helper classes in Tomcat. Can i also configure classpath in tomcat to look for the file in different directory? Any pointers will be of great help.

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

You should indeed avoid using new File() and new FileInputStream() with a relative path. For background information, see also getResourceAsStream() vs FileInputStream .

Just use an absolute path like

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

or add the given path to the classpath as shared.loader property of /conf/catalina.propeties

shared.loader = /absolute/path/to

so that you can just get it from the classpath as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM