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"))
Related
I know there are many topics out there for this but I have seem to have tried everything. I can put my file name in there and it finds it if there is a src folder,
InputStream is = context.class.getClassLoader().getResourceAsStream("file.props");
but when we put it on an apache server, a src folder is not automatically created, so it isn't finding it. I have tried placing it directly in the web-inf folder and
InputStream is = context.class.getClassLoader().getResourceAsStream("/WEB-INF" + File.separator + "file.props");
But this is always returned as null. What is the reason for this? The file exists there, why can't it find it?
You appear to be using the wrong ClassLoader. Invoking context.class.getClassLoader() provides the ClassLoader with which the ServletContext class (context.class) was loaded. What you want is the ClassLoader for the web application's classes, which would be context.getClassLoader().
Don't use the ClassLoader if you want to load your file from /WEB-INF. Instead, use the ServletContext's method for just that purpose:
// In your servlet e.g. doGet method
ServletContext app = super.getServletContext();
InputStream in = app.getResourceAsStream("/WEB-INF/file.props");
Note that using / is okay regardless of the OS, filesystem, etc.
If you really want to use the ClassLoader, take #rickz's advice and move your file.props into WEB-INF/classes.
Is there a way to read a text file which is inside a package.
Lets say that I want to access a file called "myTextFile.txt", which is in a package called "a".
I want to access it from a class called "MyClass" which is in the same package.
What would be the path to "myTextFile.txt"? And would I be able to use bufferedreader like this: BufferedReader in = new BufferedReader(new FileReader(PATH));
Where is your project compiled to? Any paths will be relative to the program's location, or the full path if you specify, not the class. Once you get that path you can put it where PATH is.
However, is there any reason you're putting that file inside a package? Shouldn't it go in some sort of resources directory?
GetResource on Class works well. ResourceLocator in Spring is also a very flexible option as well.
You can get always get resources via ClassLoader.getResourceAsStream() (or getResource()). They can also be accessed via Class.getResourceAsStream() (instead of ClassLoader). You could either use relative or absolute names (starting with /).
It sounds like you need to use one of the Class.getResource() or ClassLoader.getResource() methods:
URL url = MyClass.class.getResource("myTextFile.txt");
URL url = MyClass.class.getClassLoader().getResource("myTextFile.txt");
or
InputStream in = MyClass.class.getResourceAsStream("myTextFile.txt");
InputStream in = MyClass.class.getClassLoader().getResourceAsStream("myTextFile.txt");
See this question for a comparison, and an explanation of absolute versus relative paths.
Then you could do
new BufferedReader(new InputStreamReader(in));
InputStream is = new BufferedInputStream(
getClass().
getClassLoader().
getResourceAsStream("/a/myTextFile.txt"));
Should do the trick. Note please the structure of the arg, the root of the package is represented by "/" and so are your packages (i.e. directories)
Just input the absoulte file path. i.e. your lcoal machine path. Should work.
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.
I have a class,in which ther is a func,which opens a properties file. When i write main in the same class & call that function,i am able to open the properties file n read. but, when i am tying to call the same func in my servlet by creating instance to that class, i get file not found exception.
This is the function, which i have written in my class to read properties file. And both my class and servlet are in src folder. I am using eclipse IDE.
Code:
private void readPropertiesFileAndFieldListData() {
String PROP_FILE = "./src/fields.properties";
try {
FileReader reader = new FileReader(PROP_FILE);
BufferedReader br = new BufferedReader(reader);
ArrayList<String> field = new ArrayList<String>();
while ((str = br.readLine()) != null) {
if (!str.startsWith("#") && str.trim().length() > 0) {
// System.out.println(str);
field.add(str);
count++;
}
}
}
You're relying on the current working directory of the disk file system path. The current working directory is dependent on how the application is started and is not controllable from inside your application. Relying on it is a very bad idea.
The normal practice is to put that file in the classpath or to add its path to the classpath. Your file is apparently already in the classpath (you placed it in the src folder), so you don't need to change anything else. You should should just get it from the classpath by the class loader. That's more portable than a disk file system path can ever be.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("fields.properties");
// ...
See also:
getResourceAsStream() vs FileInputStream
Unrelated to the concrete problem, you're basically reinventing the java.util.Properties class. Don't do that. Use the following construct:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("fields.properties");
Properties properties = new Properties();
properties.load(input);
// ...
PLease write a small test, for printing the file path of "PROP_FILE" to the log or console.
it seems, that you relativ path is incorrect.
Your relative path starting point can change, depending on where your *.exe file is started.
Your test should print
File tFile = new File(PROP_FILE);
// print tFile.getAbsolutePath()
Its better to get a special class by calling
SomeClass.class.getResource(name)
Eclipse RCP from the Bundle
Bundle.getResource(ResourcePathString)
EDIT:
Please check, whether the resource is part of your *.jar. It could be, that you missed to add it to the build.properties file.
Check whether the file is existing, before you read the properties file.
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.