0

Currently I have a file in my desktop.I refer to that as

   private static String fileListFileName= "/home/sowmya/Desktop/test.txt";

I added the file to WEB-INF/model folder,I need to refer to a file that is in my WEB-INF/model/ folder How to refer to that file path in my Java file?

1 Answers1

0

You can do this to check all files inside WEB-INF folder

 String [] f=new File(getServletContext().getRealPath("WEB-INF")).list(); 

If you have below scenario and want to read properties file

SampleApp.war
   |
   |-------- myApp.properties
   |
   |-------- WEB-INF
                |
                |---- classes
                         |
                         |----- org
                                 |------ myApp
                                           |------- MyPropertiesReader.class

You have to do this

    InputStream inputStream = this.getClass().getClassLoader()  
                .getResourceAsStream("myApp.properties");
    Properties properties = new Properties();  
    System.out.println("InputStream is: " + inputStream);  
    // load the inputStream using the Properties  
    properties.load(inputStream);    

You can do it also from ServletContext

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ServletContext servletContext = getServletContext();
        String contextPath = servletContext.getRealPath(File.separator);
        PrintWriter out = response.getWriter();
        out.println("<br/>File system context path (in TestServlet): " + contextPath);

    }

Another way

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream stream = classLoader.getResourceAsStream("FileName");

    if (stream == null) {
      // File not nound
    } else {
     // User stream object 
    }
Subodh Joshi
  • 10,006
  • 23
  • 84
  • 177
  • You should not be listing files with ServletContext#getRealPath, see http://stackoverflow.com/a/12160863/498531 – jpangamarca Nov 30 '16 at 14:01