Tomcat JVM - Root folder reference [duplicate] - java

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 7 years ago.
The following code returns the path to the war folder (i.e. /ROOT/):
getServletContext().getRealPath("/");
I need to go one folder up from this point, how do I go about doing that?
I have tried the following:
final String path = getServletContext().getRealPath("./");
final String path2 = getServletContext().getRealPath("../");
final String path3 = getServletContext().getRealPath(".../");
I need so save files outside of the ROOT folder, but only one level up, so that everytime I update my website, it doesn't replace the physically uploaded files within the ROOT folder, and rather only touch the web site files.
Thanks

We don't even know if your WAR files are unpacked: Tomcat can well deploy them without unzipping, which leaves you with a non-filesystem-path.
As discussed in the comments, it's bad practice to do this, you should rather figure out where to store the data - for example: database, external storage, somewhere in the file system. Then "just" provide a separate download option for those files - individually or zipped - through your web application.

Another solution you can use is a symbolic link to an external folder.
You can create a folder out side your project let's say for the example at the same level of the webapps folder in your tomcat path.
We will name uploads for the example.
Now in your deploy script (assuming you have one), you can easily create symbolic link from the uploads folder to a folder inside your project.
It will allow you to get the files from inside of your project, and when you re-deploy, the files are not delete.
For example:
ln -s /var/lib/tomcat6/uploads /var/lib/tomcat6/webapps/myWebApp/uploads
The example above is for my distro of tomcat6 but you can change the path to work with your setup.
This answer uses 3 assumptions:
Your WAR file is unpacked.
You have a deployment script and if not you can easily create a bash script
to do so.
The solution you need is for a non distributed setup (each server holds its own files).
Liron

You have to use the File's API over war's location.
File root = new File(getServletContext().getRealPath("./"));
String parent = root.getParent();
String parentParent = new File(parent).getParent();

Related

How to download file from a URL and save/replace it in a folder using Java 8?

So, I need to download 2 csv files which include pricing details for some AWS services.
https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AWSStorageGateway/current/index.csv
https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonS3/current/index.csv
I need to download the files from the URLs and store it in separate folders to avoid conflicts. Such as, the first index.csv file will be downloaded to a folder AWSStorageGateway and the second one to folder AmazonS3.
Or another approach could be to store those files in 1 folder by changing filenames like AWSStorageGateway.csv and AmazonS3.csv. If the files already exist, it needs to be replaced with the new one.
The project uses Java 8 and Spring MVC. I don't want to use any external libraries. Is NIO package enough to handle this?

Upload file to Spark Java

I am trying to create a folder which contains uploaded files. I have seen some examples that saving files into the absolute folder such as D:/tmp or Home directory. My question is I am trying to put my uploaded files into a folder which is inside the project folder.
I also tried to get project folder using like this :
public static String getProjectFolder(){
return System.getProperty("user.dir")+"/";
}
Result become something like this, and file not found exception inside the Html file!
http://localhost:1234/Users/USER_NAME/Documents/java/PROJECT_NAME/upload/genres/action.jpg
What is the best way to add folder into my project? Or should I use hardcoded folder for it ?
You need to set the folder that you want to upload files to as the static files folder using staticFiles.externalLocation().
The only folder the client can reach, either for getting content from OR uploading to, is the folder you set using the static files location API staticFiles.externalLocation(). You can see also an example for that here.
When I run my server locally, I define it to be:
staticFiles.externalLocation(System.getProperty("user.dir") + "/src/main/resources");
This is regarding what your question.
You might run into an issue though. Because now you probably have two locations that you want public:
The resources folder (with all the JavaScripts, CSSs, etc. Typically /src/main/resources)
Upload folder (to let the user upload files)
Having both of these the same location is not a good practice. I managed to resolve that by creating a symbolic link called files inside the public folder.
abcmbp:resources abc$ pwd
/Users/abc/dev/wspace/proj1/src/main/resources
abcmbp:resources abc$ ls -l files
lrwxr-xr-x 1 abc staff 27 Mar 3 21:20 files -> /Users/abc/appUploadFolder/
Then, in the post handle of the uploading path, I give this folder as the destination, and this way I have a separation between resources and uploaded files.

How do I configure the server so that It stores the dynamically created files in the specified folder not under the bin folder?

I have developed a web application which will create an xml file based on the user Input. It has some more functionality. I configured my application to store the xml file(s) in the project root folder. When I run it through eclipse It stores in the specified location. But If I manually put the war file in apache tomcat and run the application those newly created xml files are going into bin directory since I used relative path. Now I dont want it to be created under bin directory. I want those files to be created somewhere local in the system. Is there any way to do it ? Or else what is the best way to deal with those xml files. I am using spring MVC.
You could use a variable in your code would contain the first part of the path (the real location where you want to write the file). And inject the value of that variable from a properties file, that way you wouldn't hardcode anything, and still would be able to provide only the relative path in your code.

Current directory of a web app in netbeans

I am working on a web app i have java files in it which uses certain files.I want to specify these files using relative path in java so that it doesn't produce mobility issue.But Where should i place a file in a web app so that i can use relative path.? I have tried placing the files under source package, web folder, directly under the web-application.Please help.Thanks in advance
The simplest way to get the current directory of a java application is :
System.out.println(new File(".").getAbsolutePath());
Like that you can consider the given path as the root of your application.
Cheers,
Maxime.
Read the file as a resource. Put it somewhere in the src. For instance
src/resources/myresource.txt
Then you can just do
InputStream is = getClass().getResourceAsStream("/resources/myresource.txt");
Note: if you are using maven, then you are more accustomed to something like this
src/main/resources/myresource.txt
With maven, everything in the main/resources folder gets built to the root, so you would leave out the resources in your path
InputStream is = getClass().getResourceAsStream("/myresource.txt");

Java (maven web app), getting full file path for file in resources folder?

I'm working with a project that is setup using the standard Maven directory structure so I have a folder called "resources" and within this I have made a folder called "fonts" and then put a file in it. I need to pass in the full String file path (of a file that is located, within my project structure, at resources/fonts/somefont.ttf) to an object I am using, from a 3rd party library, as below, I have searched on this for a while but have become a bit confused as to the proper way to do this. I have tried as below but it isn't able to find it. I looked at using ResourceBundle but that seemed to involve making an actual File object when I just need the path to pass into a method like the one below (don't have the actual method call in front of me so just giving an example from my memory):
FontFactory.somemethod("resources/fonts/somefont.ttf");
I had thought there was a way, with a project with standard Maven directory structure to get a file from the resource folder without having to use the full relative path from the class / package. Any advice on this is greatly appreciated.
I don't want to use a hard-coded path since different developers who work on the project have different setups and I want to include this as part of the project so that they get it directly when they checkout the project source.
This is for a web application (Struts 1.3 app) and when I look into the exploded WAR file (which I am running the project off of through Tomcat), the file is at:
<Exploded war dir>/resources/fonts/somefont.ttf
Code:
import java.io.File;
import org.springframework.core.io.*;
public String getFontFilePath(String classpathRelativePath) {
Resource rsrc = new ClassPathResource(classpathRelativePath);
return rsrc.getFile().getAbsolutePath();
}
In your case, classpathRelativePath would be something like "/resources/fonts/somefont.ttf".
You can use the below mentioned to get the path of the file:
String fileName = "/filename.extension"; //use forward slash to recognize your file
String path = this.getClass().getResource(fileName).toString();
use/pass the path to your methods.
If your resources directory is in the root of your war, that means resources/fonts/somefont.ttf would be a "virtual path" where that file is available. You can get the "real path"--the absolute file system path--from the ServletContext. Note (in the docs) that this only works if the WAR is exploded. If your container runs the app from the war file without expanding it, this method won't work.
You can look up the answer to the question on similar lines which I had
Loading XML Files during Maven Test run
The answer given by BobG should work. Though you need to keep in mind that path for the resource file is relative to path of the current class. Both resources and java source files are in classpath

Categories