How to get file path of a file using Java Code?


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:

File Path: /Users/dev/Downloads/demo/code2care/data.txt


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");
        }
    }

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap