This question already has an answer here:
How can I read file from classes directory in my WAR?
(1 answer)
Closed 10 years ago.
i am try to read the file using ServletContext `
InputStream is = servletContext.getResourceAsStream(path)
the value of path is :
path = D:\Assignments\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\HelpGuide\GeneratedReports\userDetail.pdf`
the userDetail.pdf file is exist in given path , but when i try to get the resource as stream using servlet context define as above , the value of is is null .
This is because the getResourceAsStream looks to a path relative to the context root.
Checkout javadoc of servlet context and especially the "getResource" part: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)
You should use a relative path and put your pdf in your classpath, that would be a better practice as your app will not rely on an absolute path.
This is such a bad idea, as the servlet is telling you.
Put that PDF in the CLASSPATH (e.g. WEB-INF/classes of your WAR) and read it as an InputStream from the servlet context.
Absolute paths are the wrong way to go for web apps.
Related
This question already has answers here:
How to get the current working directory in Java?
(26 answers)
Closed 3 years ago.
Part of my (java) code needs to access a database. When opening a connection it checks if the actual database file exists (I use sqlite). I want to make my code portable, so I want to avoid hard coding the path of the database file. Is there anyway in java to get the path of the .java file? Because I know exactly where the database is from the .java file accessing it.
I've tried using current directory with File but it doesn't give me the path of the actual .java file. When I use android studio the current directory is different than when I simply use a terminal.
The best way to get the path information would be using Paths and Path class from the java.nio. You can input an absolute path or relative path to the Paths.get(String str) to get the Path.
To get the project directory, you can use:
Paths.get(System.getProperty(“user.dir”))
Paths.get(“”)
It will get the complete absolute path from where your application was initialized.
The Paths.get() method will return a Path Object, on which you can call toString() or toUri() to get the path. Hope this helps.
Javadocs - Paths
This question already has answers here:
Use properties file in Spring [closed]
(2 answers)
Closed 7 years ago.
I have a webapplication on Java spring. I need to read application specific settings when the application will be initialized. I have added app.properties under WebContent/WEB-INF but I am not able to get that file from the class.
If I provide
InputStream input = servletContext.getResourceAsStream("WEB-INF/spring.properties");
prop.load(input);
then it is showing file is not present. I can not use absolute path. What will be the path?
From the Javadoc ServletContext.getResource:
The path must begin with a / and is interpreted as relative to the
current context root, or relative to the /META-INF/resources directory
of a JAR file inside the web application's /WEB-INF/lib directory.
Therefore try
InputStream in = servletContext.getResourceAsStream("/WEB-INF/<filename>");
This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 6 years ago.
Properties file location is WEB-INF/classes/auth.properties.
I cannot use JSF-specific ways (with ExternalContext) because I need properties file in a service module which doesn't have a dependency on a web-module.
I've already tried
MyService.class.getClassLoader().getResourceAsStream("/WEB-INF/classes/auth.properties");
but it returns null.
I've also tried to read it with FileInputStream but it requires the full path what is unacceptable.
Any ideas?
Several notes:
You should prefer the ClassLoader as returned by Thread#getContextClassLoader().
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.
The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.
classLoader.getResourceAsStream("/auth.properties");
If you opt for using the Thread#getContextClassLoader(), remove the leading /.
The JSF-specific ExternalContext#getResourceAsStream() which uses ServletContext#getResourceAsStream() "under the hoods" only returns resources from the webcontent (there where the /WEB-INF folder is sitting), not from the classpath.
Try this:
MyService.class.getClassLoader().getResourceAsStream("/auth.properties");
Reading files with getResourceAsStream looks on the classpath to find the resource to load. Since the classes directory is in the classpath for your webapp, referring to the file as /auth.properties should work.
ResourceBundle (http://download.oracle.com/javase/6/docs/api/java/util/ResourceBundle.html) resolve most of the problems with a relative/absotule path for Properties Files.
It uses the the Resource class and point it to a Dummy Class to make reference to a properties file.
For example:
You a have file called MAINProperties.properties and inside it there is a property:
mail.host=foo.example.com
Create a Dummy Class called MAINProperties without nothing.
Use the following code:
ResourceBundle.getBundle("com.example.com.MAINProperties").getProperty("mail.host")
And That's it. No InputStreams Required.
P.D. Apache Commons has a Library Called Apache Commons Configuration that has a lot of capabilities (reloadable files, multiple domain types) that could be used in combination of the above.
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 7 years ago.
I have a jsp file in the root of .war file.
and then I have a folder named STUFF.
How do I get access to the file read.txt inside STUFF?
/Name_of_war/STUFF/read.txt is the correct path?
The webapp-relative path is /STUFF/read.txt.
You could use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path. This way you can use it further in the usual java.io stuff which actually knows nothing about the web context it is running in. E.g.
String relativeWebPath = "/STUFF/read.txt";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// Do your thing with File.
This however doesn't work if the server is configured to expand the WAR in memory instead of on disk. Using getRealPath() has always this caveat and is not recommended in real world applications. If all you ultimately need is just getting an InputStream of that file, for which you would likely have used FileInputStream, you'd better use ServletContext#getResourceAsStream() to get it directly as InputStream:
String relativeWebPath = "/STUFF/read.txt";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// Do your thing with InputStream.
If it is located in the classpath, or you can add the folder to the classpath,
How about:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream(fileName);
This question already has answers here:
How to save generated file temporarily in servlet based web application
(2 answers)
Closed 6 years ago.
I have recently created a web project in Java using eclipse. I have a servlet which includes a timer task. This timer tasks calls the "writeList" method of an XML Writing class that I have created. This all works fine, and I have verified that it runs every minute using System.out.
When I run my XML Writing class from within eclipse as an application, it works fine. The file is outputted to 'WebContent/test.rdf' without any problems.
However, when it is called by the timer task in my servlet, I am getting the following error:
java.io.FileNotFoundException: WebContent/Test.rdf(No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at com.XMLWriter.writeList(XMLWriter.java:58)
at com.ServerTimer$1.run(ServerTimer.java:30)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
The code at line 58 of XMLWriter is as follows:
fileOut = new FileOutputStream("WebContent/TEST.rdf");
model.write(fileOut);
fileOut is a FileOutputStream, and model is an instance of a Jena model, as I am working with RDF.
Any help would be appreciated, I have been stuck with this for days now! Any questions just let me know!
EDIT: So it is working now, but I want to write the file to the 'WebContent' directory of my Web Project. Is there any way of doing this automatically? I can't get the system to dynamically find that directory.
You should never rely on relative paths that way. Using relative paths in Java IO is asking for portability trouble. The java.io.File knows nothing about the web application context it is running in. The actual path would be dependent on the current working directory, which is not per se the same in all environments and depends on the way how you started the server/application. It may become relative to for example C:/Tomcat/bin and your TEST.rdf is obviously not there. Always use absolute paths, i.e. use the full disk file system path.
In case of a JSP/Servlet webapplication you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path which you can use further in Java IO stuff. A relative web path is rooted in the public webcontent. Assuming that /TEST.rdf is located in the root of the public webcontent, then you can get an absolute disk file system path for /TEST.rdf inside a servlet the following way:
String relativeWebPath = "/TEST.rdf";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
It's because the directory does not exist. Either create the directory (programatically or offline) or create the folder on the base path.