Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real path of a file in a Java class

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 ?

like image 411
Emilie Avatar asked Sep 27 '12 11:09

Emilie


People also ask

How do I fetch a file path?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

What is getCanonicalPath in Java?

The getCanonicalPath() method is a part of Path class. This function returns the Canonical pathname of the given file object. If the pathname of the file object is Canonical then it simply returns the path of the current file object. The Canonical path is always absolute and unique, the function removes the '.


1 Answers

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.

like image 149
duffymo Avatar answered Oct 05 '22 21:10

duffymo