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);
Related
This question already has answers here:
How to get a path to a resource in a Java JAR file
(17 answers)
Closed 4 years ago.
I was using the following code to read a file from the classpath:
Files.readAllBytes(new ClassPathResource("project.txt").getFile().toPath())
This worked fine when project.txt was in src/main/resources of my WAR. Now I refactored code and moved certain code to a JAR. This new JAR now includes src/main/resources/project.txt and the code above. Now I get the following exception when reading the file:
java.io.FileNotFoundException: class path resource [project.txt]
cannot be resolved to absolute file path because it does
not reside in the file system:
jar:file:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib/viewer-1.0.0-SNAPSHOT.jar!/project.txt
I'm still executing the WAR in a Tomcat container.
How can I fix this?
You cant refer the file from jar the way you do it in from resources. Since the file is packaged inside the jar you need to read it as resource.
You have to read the file as resource using classloader.
sample code:
ClassLoader CLDR = this.getClass().getClassLoader();
InputStream inputStream = CLDR.getResourceAsStream(filePath);
If you are using java 8 and above then you can use below code using nio to read your file:
final Path path = Paths.get(Main.class.getResource(fileName).toURI());
final byte[] bytes = Files.readAllBytes(path);
String fileContent = new String(bytes, CHARSET_ASCII);
I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.
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.
I need to be able to access my web application's css files, that are stored under src/main/resources/styles, from the backend java controller. I want to use them for creating PDF output with iText.
In other words, I want to do something like this:
CssFile cssFile1 = XMLWorkerHelper.getCSS(new FileInputStream("src/main/resources/styles/my.css"));
However, I'm clearly not going about this correctly, as I am receiving Exceptions like this:
java.io.FileNotFoundException: styles\standard.css (The system cannot find the path specified)
How can a retrieve these files in the controller?
I tried this, but it did not work, same error:
String rcp = econtext.getRequestContextPath();
CssFile cssFile1 = XMLWorkerHelper.getCSS(new FileInputStream(rcp + "src/main/resources/styles/my.css"));
The FileInputStream operates on the local disk file system and all relative paths are relative to the current working directory, which is the local disk file system folder which is been opened at exactly the moment the JVM is started. This is definitely not the root of src/main/resources folder.
Given that the /src/main/resources is recognizable as a Maven folder structure for root of classpath resources, then you just need to obtain it as classpath resource by ClassLoader#getResourceAsStream() instead.
InputStream input = getClass().getResourceAsStream("/styles/standard.css");
// ...
Or if the class is possibly packaged in a JAR loaded by a different classloader.
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("styles/standard.css");
// ...
See also:
getResourceAsStream() vs FileInputStream
Thats because the JSF is a web app.
Now move the styles/my.css to WEB-INF/styles/my.css this ensures the files your accessing within the controller are part of the WebApp
and now you can access the resource using
XMLWorkerHelper.class.getResourceAsStream("styles/my.css")
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.