Search code examples
javajspnetbeansglassfishglassfish-3

Opening input file using java code in JSP


I am using JSP on NetBeans.

In the java code, I am trying to read data from a file. First I open the file by specifying its path.

Because my code runs on a server (GlassFish), I would like to have my file path independent of the machine where it runs. Therefore, I want to start the path with the folder name that contains the file which is saved on the root of the project directory. I tried so hard to achieve that but I couldn't.

I read online and I found this way, but it still doesn't work:

<%

  //building the tree here.
GraphBuilder tree = new GraphBuilder("${pageContext.request.contextPath}\\src\\java\\Database\\OptimizedFullTermFile.pad");

%>

Can anyone help? Thank you.


Solution

  • Just read it from the classpath. Given that you're using the typical src folder representing the Java source code (the Java package/class structure), I assume that the file OptimizedFullTermFile.pad is placed in the Java package java.Database (eek, a capital in package name? lowercase it all). In that case, it's already in the classpath and thus you can just get it straight from there as follows:

    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("java/Database/OptimizedFullTermFile.pad");
    // ...
    

    As to your failed attempt: the EL ${pageContext.request.contextPath} isn't ever going to work in a scriptlet. Even if it did, it's not the right thing, it returns the context path in the webapp URL which is absolutely not part of the local disk file system path, let alone the classpath. Using scriptlets is strongly discouraged since a decade, by the way.

    See also: