Reputation: 668
I get a file like that :
String myFile = "D:/dev/workspace/MyProject/WebContent/stats/stats.csv";
File statsFile = new File(myFile);
But I want to only have the relative path as stats/stats.csv
. I don't want to have to write the complete path in my code.
In a servlet, I do it this way :
File statsFile = new File(this.getServletContext().getRealPath("/") + "stats/stats.csv");
But here it is not in a servlet. So what is the equivalent way in a java class ?
Upvotes: 6
Views: 10019
Reputation: 668
I found a solution.
I can use my JSP to use File statsFile = new File(this.getServletContext().getRealPath("/") + "stats/stats.csv")
and then pass statsFile
to my class.
Upvotes: 0
Reputation: 213193
String basePath = "D:/dev/workspace/MyProject/WebContent";
String absolutePath = "D:/dev/workspace/MyProject/WebContent/stats/stats.csv";
String relativePath = new File(basePath).toURI().
relativize(new File(absolutePath).toURI()).getPath();
System.out.println(relativePath); // stats/stats.csv
basePath
is the path, relative to which you want to get Relative Path
.
Upvotes: 0
Reputation: 308733
You should put it in the CLASSPATH and read it from an InputStream
acquired using getResourceAsStream()
. It's the path-independent way to access a file.
Upvotes: 2