There are multiple ways to get the file path for a file in java, let's see a few examples,
Example 1: Using File class
import java.io.File;
/**
* Get File Path using File class.
*/
public class FilePathExample {
public static void main(String[] args) {
File file = new File("data.txt");
String filePath = file.getAbsolutePath();
System.out.println("File Path: " + filePath);
}
}
Output:
Example 2: Using File class
Path path = Paths.get("data.csv");
String absolutePath = path.toAbsolutePath().toString();
Example 3: Using ClassLoader
public static void main(String[] args) throws URISyntaxException {
ClassLoader classLoader = FilePathExample.class.getClassLoader();
URL resource = classLoader.getResource("data.txt");
if (resource != null) {
Path path = Paths.get(resource.toURI());
System.out.println("File path: " + path);
} else {
System.out.println("File not found");
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!