Get real file path in Java class

I get a file like this:

String myFile = "D:/dev/workspace/MyProject/WebContent/stats/stats.csv"; File statsFile = new File(myFile); 

But I want to have only a relative path like stats/stats.csv . I do not want to write the full path in my code.

In the servlet, I do this:

 File statsFile = new File(this.getServletContext().getRealPath("/") + "stats/stats.csv"); 

But here it is not in the servlet. So what is equivalent in java class?

+6
source share
3 answers

You should put it in CLASSPATH and read it from the InputStream obtained with getResourceAsStream() . This is a path-independent way to access the file.

+2
source
 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 you want the Relative Path relative to.

0
source

I have 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.

0
source

Source: https://habr.com/ru/post/926392/


All Articles