Save a file at runtime inside WebContent in Java Web project [duplicate] - java

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.

Related

How can I get the Url of file that is outside the jar?

I have deployed spring boot app in exploded mode using maven-assembly-plugin. I have made config folder from project’s resource folder.
The problem is that I am not able to get the url to access the file that is in the config folder.
How can I get the url of the file that I have uploaded and stored at this config folder.
File structure
Target folder:
+springdemo-0.0.1-application.zip
+config
+myfolder
-oldfile.png
+springdemo-0.0.1.jar //running this jar file
+start.sh
-springdemo-0.0.1.jar
I want URL of files stored in myfolder. This url will be accessed by 3rd party(for ex. Picasso) to get file data. I am unable to get correct url pointing to this myfolder files.
Its easy, you need to provide the full path of the external application.properties file than what is present in your source code during the startup of the spring-boot.jar application at runtime.
Example: java -jar -Dspring.config.location=file://<>
This external file takes precedence over the one in our jar file.
Note: Not a SpringBoot-specific answer, just the simple Java way.
You can only try to guess the location of the file because there's no way to know the working directory when a Java application is run.
For example, you could try a very simple approach if you control how the Java application is executed:
var configFile = new File("config/application.properties");
This will works as long as the process is started from the same directory where start.sh is (which seems like what you intend).
If it doesn't work, try printing the working directory like this first:
System.out.println("WRK DIR = " + new File(".").getAbsolutePath());
This will tell you what the relative path to your file should be.
So, if this prints <root-dir>/springdemo and you know your config file is under <root-dir>/springdemo/mydir/config/, then the file path should be:
new File("mydir/config/application.properties");
By the way, you can easily read the file with:
// read file into List of lines
Files.readAllLines(configFile);
// specifically, for properties file
var props = new Properties();
props.load(new FileInputStream(configFile));
If for whatever reason you need an URL object instead of a File, it's easy, just call:
URL url = configFile.toURI().toURL()
If you want ALL files under the config dir, you can list them first with:
File[] files = configFile.getParentFile().listFiles();
if (files != null) {
for (File file : files) {
// use file?
}
}

Unzipping a file returns a FileNotFoundException when creating a directory [duplicate]

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.

How to edit a Maven resources file from Java? [duplicate]

I am doing the following,
String str = "this is the new string";
URL resourceUrl = getClass().getResource("path_to_resource");
File file = new File(resourceUrl.toURI());
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(xml);
writer.close();
In the above code I am trying to write to a resource file contained in one of my java packages. After executing the code, my program executes fine but the file just updates the properties file in web-INF and not into the package where it is stored. Can anyone please help me figure how can I achieve that or what am I doing wrong here? Thanks a lot.
You should not be trying to write to a file stored with your application classes. Depending on the application server, the location you are trying to write to may not be writable or the application may be running from an application archive (a .war file).
You should use an external folder to store configuration and other application data. Typically, you specify this folder via an environment variable or a property specified during deployment.

FileInputStream in Spring MVC fails to find file

I am working on a SpringMVC project which runs a number of automated tests on a database. The access details for this database are located in a .properties file. This file is located within the project directory.
FileInputStream fis = new FileInputStream("batch-dm.properties");
propFile = new Properties();
propFile.load(fis);
As the file is stored in the project directory the FileInputStream should be able to access it no?
If I provide the absolute path e.g.
FileInputStream fis = new FileInputStream("C:/workspace/Project/batch-dm.properties");
It recognises the file and runs properly.
Do I need to sore this file in a different location because it is a Spring MVC project?
Thanks
Just to clear out your mind, try to see what is the value that outputs System.getProperty("user.dir") (let's call it A), this will print the complete absolute path from where your application was initialized, more specifically it will print the directory from where the JVM was started.
If you doesn't supply a parent path to the file that you are trying to open, the (A) path is taken by default and the file is looked inside that directory. So please, have in mind that.
Aditional information
If you absolutely need that file you should include it in your project so you can access it as a resource. Resource is a file that is included in your project and came bundled with the generated .jar or .war for re distribution.
My advice is to put the file in the package and use as a resource as it the safer way to work with external resources that should be shipped with your project.
Take a deeper look at this post for more about practical way of handling resources.
Please refer below link:
https://stackoverflow.com/a/2308388/1358551
You may have to use getResourceAsStream().

Trying to update the file in src/web/prod folder (jsp)

I am using jboss, eclipse and svn together. I have to files in my test folder: test/create.jsp and test/data.txt . What I want to do is when I call my create.jsp it will update my data.txt . Obviously I want my data.txt to stay where it is as other scripts are tryong to read from it.
I have tried dozens of new ways to put the path to my File object but for some reason it creates the file under jboss war folders.
Tried:
ServletContext app = getServletContext();
String path1 = app.getRealPath("/");
File f = new File(path1);
// AND
File f = new File("../../data.txt");
Assuming that /test folder is located in the webcontent, then you need the following:
String absolutePath = getServletContext().getRealPath("/test/data.txt");
File file = new File(absolutePath);
or
String webcontentRoot = getServletContext().getRealPath("/");
File file = new File(webcontentRoot, "test/data.txt");
Do you see it? The Java IO only understands local disk file system paths, not URL's or paths outside the context. The ServletContext#getRealPath() is to be used to convert a relative web path to an absolute local disk file system path which in turn can be used further in the usual Java IO stuff. You should never use relative paths in Java IO stuff. You will be dependent on the current working directory which may differ per environment/situation.
That said, you normally don't want to write files to the webcontent. They will get lost whenever you redeploy the WAR. Rather create a fixed disk file system path somewhere else outside the webapp and make use of it. Or even better, make use of an independent SQL database :)

Categories