FileInputStream and FileNotFound Exception - java

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.

You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.

You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");

String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.

check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());

I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Related

How to get the actual source path in Struts 2?

I have a little problem with Struts 2 when I try to get the context path :
ServletActionContext.getServletContext().getRealPath("\\WebContent\\resources\\img\\");
I got this path:
C:\Users\killian\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SiteWebAdministrable\WebContent\resources\imgicone.jpg
Why the exact source path ?
Because i need to upload and save images for an admin website to control background and without the actual path i cannot save images in the resources path...
So i save the path with the name and extension in the database (no problem), and i need to save the image in the resource directory (image problem...)
Can someone help me please ? Did i forgot something ?
This question is the answer ?
How do you get the project path in Struts 2?
servletContext.getServletContext().getRealPath("/resources/img/name_of_image.png")
So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/demo.war/ which you should be able to further use in File or FileInputStream.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "demo.png";
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/demo.png");
getRealPath() is unportable; you'd better never use it
Use getRealPath() carefully.
If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/demo.png")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/demo.png"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");

error in using getAbsolutePath function in java

My xml file is place in this path "C/users/input/abc.xml".
I am executing code from "c/users/prg/abc.java"
Using getAbsolutePath function on Xml file object but i am getting this"c/users/prg/abc.xml" as result.
i have already tried using the below code:
File file = new File("C:\\users\\Input\\abc.xml");
String absPath = file.getAbsolutePath();
System.out.print(absPath);
output: C\users\prg\abc.xml
is it Classpath issue? or Am i doing something wrong?
The absolute path is like below
C:\users\Input\abc.xml
Once again rebuild ur application. What your expecting from us.
Regards,
Sekhar
I Think the error is occurring due to wrong class path.
Check the class path if it is right and let me know.

The use of getResourceAsStream for BufferedReader and InputStream

I am writing webApp that use jsp file to call java class directly to get results.
The JSP file is like:
<%
String queryKey = request.getParameter("id");
int jobID = Integer.parseInt(queryKey);
out.println(jobID);
ArrayList<Integer> myTopList = JobRecByBoWJaccard.topJobsByBoW(jobID);
%>
In java classes the files are accessed through:
BufferedReader br = new BufferedReader(new FileReader("WebContent/StopWords/stop-words-english1.txt"));
and
private InputStream modelInputT = new FileInputStream("WebContent/OpenNLP_Models/en-token.bin");
The tomcat cannot find the referenced files and someone said use getResourceAsStream, but that is for servlets. I call the java class directly without any servlets.
private InputStream modelInputT = = this.getClass().getClassLoader().getResourceAsStream("WebContent/OpenNLP_Models/en-token.bin");
This cause java class cannot find the file as well. Need help and how to make changes to these java classes?
The tomcat cannot find the referenced files ...
That is because the pathnames are incorrect unless the JVM's current directory is the parent directory of the "WebContent" directory. When you use FileInputStream to open a file, relative pathname are resolved relative to the current directory of the JVM when it was launched.
... and someone said use getResourceAsStream, but that is for servlets.
No. That's not correct either. That method is not "for servlets". The purpose of that method is to open a resource that is on the class / classloader's classpath. If your "WebContent/StopWords/stop-words-english1.txt" is in the webapp's "/WEB-INFO/classes" or in a JAR file in "/WEB-INFO/lib", then getResourceAsStream will find it.
In your case, it seems like you are talking about the "WebContent" directory that corresponds to the default servlet.
In that case, read this Q&A - How can I get real path for file in my WebContent folder?.
So if you are trying to access those files from within a JSP, it seems as if you should be writing this:
new FileReader("WebContent/StopWords/stop-words-english1.txt")
as this:
new FileReader(getServletContext().getRealPath(
"/StopWords/stop-words-english1.txt"))

getResource with parent directory reference

I have a java app where I'm trying to load a text file that will be included in the jar.
When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine.
However, if I try getClass().getResource(/a/b/../"), then I get a null URL back.
It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful.
The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library.
final String name = "/a/b/../";
final String normalizedName = FilenameUtils.normalize(name, true); // "/a/"
getClass().getResource(normalizedName);
The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?

Programmatically reading static resources from my java webapp [duplicate]

This question already has answers here:
How to find the working folder of a servlet based application in order to load resources
(3 answers)
Closed 6 years ago.
I currently have a bunch of images in my .war file like this.
WAR-ROOT
-WEB-INF
-IMAGES
-image1.jpg
-image2.jpg
-index.html
When I generate html via my servlets/jsp/etc I can simple link to
http://host/contextroot/IMAGES/image1.jpg
and
http://host/contextroot/IMAGES/image1.jpg
Not I am writing a servlet that needs to get a filesystem reference to these images (to render out a composite .pdf file in this case). Does anybody have a suggestion for how to get a filesystem reference to files placed in the war similar to how this is?
Is it perhaps a url I grab on servlet initialization? I could obviously have a properties file that explicitly points to the installed directory but I would like to avoid additional configs.
If you can guarantee that the WAR is expanded, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system which you can further use in the usual Java IO stuff.
String relativeWebPath = "/IMAGES/image1.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...
However, if you can't guarantee that the WAR is expanded (i.e. all resources are still packaged inside WAR) and you're actually not interested on the absolute disk file system path and all you actually need is just an InputStream out of it, then use getServletContext().getResourceAsStream() instead.
String relativeWebPath = "/IMAGES/image1.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
See also:
getResourceAsStream() vs FileInputStream
Use the getRealPath method of ServletContext.
Ex:
String path = getServletContext().getRealPath("WEB-INF/static/img/myfile.jpeg");
This is relatively straight forward you simply use the class loader to fetch the files from the class plath. :
InputStream is = YourServlet.class.getClassLoader().getResourceAsStream("IMAGES/img1.jpg");
There are a few other getResoruce classes that are worth looking at. Also you don't have to fetch the class loader through the class variable on your servlet. Any class that you happen to know has been loaded by the container should work .
If you know the relative location of the files you could ask the runtime about the exact location using
Thread.currentThread().getContextClassLoader().getResource(<relative-path>/<filename>)
This would give you an URL to the location where the specified image can be found. This URL can be used to read the specified file or you can split it to use the different parts of the URL for further processing.

Categories

Resources