Reputation: 41
I am using NetBean and glassFish for developing jsp website and its server. In the server side, I have a java class which generate a text file using FileWriter:
FileWriter writer = new FileWriter("the-file-name.txt", true);
But I found that this file was saved in the directory of glassfish:
C:\Program Files (x86)\glassfish-4.0\glassfish\domains\domain1\config
Also, by checking the path by the code:
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
the result is also the same with the above path.
How can I get the correct relative path, whether the path of the project or the path of this java file?
Upvotes: 0
Views: 2855
Reputation: 769
In Servlet
String filePath = getServletContext().getRealPath("/").replace("\\", "/");
In JSP
String filePath = session.getServletContext().getRealPath("/").replace("\\", "/");
Upvotes: 0
Reputation: 372
This gets the location of the class/jar you are running:
String path = System.getProperty("user.dir");
The string path holds the absolute directory, and using somthing like
path = path.replace("jars", "");
, you can find the root directory for the application. For example, if the jar is in the directory C:\Program Files\Example\jars
, this would set path to
C:\Program Files\Example\
Upvotes: 1