Help Save Code2care! 😢

I've lost 99% of my revenue to AdBlockers & AI. Your support could be the lifeline that keeps this passion project alive!

Buy Code2care a Coffee QR Code

Scan to Buy Me A Coffee and help me continue coding for you!

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

You can download this article in various formats for your convenience. Choose from the options below:

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

Author Info:

Rakesh (He/Him) has a Masters Degree in Computer Science with over 15+ 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 | Search