0

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
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Vijay Selvaraj
  • 519
  • 2
  • 6
  • 15

1 Answers1

1

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");
// ...
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555