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

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 :)

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.

Where do I put files to be read by java.io.FileReader?

I'm using java.io.FileReader:
FileReader fileReader = = new FileReader(filepath)
When running locally, a typical filepath would be
"/Users/acypher/Desktop/enrollment.json"
Then, when I deploy to Tomcat on AWS, I want to put the file somewhere in the build that FileReader can find -- any place is fine with me, but I haven't been able to find any location that works, since I don't know what root directory FileReader is using.
The .war expands to a folder which includes META-INF and WEB-INF subfolders. WEB-INF contains a "classes" folder, which contains files that are locally in my src/main/resources/ folder, so that seems like a good location. But I don't know how to set the filepath to refer to this location.
I'm using IDEA with Spring Boot.
The /src/main/resources/ is definitely the way to go. You can access the files in this folder with the methods Class.getResource(String) or Class.getResourceAsStream(String) (see: https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)).
For example, if you have your file in /src/main/resources/myFolder/myFile.myExt, you can either call:
this.getClass().getResource("myFolder/myFile.myExt")
this.getClass().getResourceAsStream("myFilder/myFile.myExt")
which, in a static context, where you don't have the this reference, become, respectively:
MyClass.class.getResource...
MyClass.class.getResourceAsStream
In the first case you should (I didn't verify it myself) be able to create a File instance like this: File file = new File(this.getClass().getResource("myFolder/myFile.myExt").toURI()), and from that the FileReader instance; while in the second case, you have at your disposal the InputStream which you can use to read the file.

Save a file at runtime inside WebContent in Java Web project [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.

Dynamic filepath in Java (writing and reading text files)

Okay, so I want to read a file name myfile.txt and let's say I'll be saving it under this directory:
home/myName/Documents/workspace/myProject/files myfile.txt
hmmm.. I want to know what I should pass on the File(filePath) as my parameter... Can I put something like "..\myfile.txt"? I don't want to hard code the file path, because, it will definitely change if say I open my project on another PC. How do i make sure that the filepath is as dynamic as possible? By the way, I'm using java.
File teacherFile = new File(filePath);
You can references files using relative paths like ../myfile.txt. The base of these paths will be the directory that the Java process was started in for the command line. For Eclipse it's the root of your project, or what you've configured as the working directory under Run > Run Configurations > Arguments. If you want to see what the current directory is inside of Java, here's a trick to determine it:
File currentDir = new File("");
System.out.println(currentDir.getAbsolutePath());
You can use relative paths, by default they will be relative to the current directory where you are executing the Java app from.
But you can also get the user's home directory with:
String userHome = System.getProperty("user.home");
You can do it:
File currentDir = new File (".");
String basePath = currentDir.getCanonicalPath();
now basePath is the path to your application folder, add it the exact dir / filename and you're good to go
You can use ../myfile.txt However the location of this will change depending on the working directory of the application. You are better off determining the base directory of you project is and using paths relative to that.

Categories