Java IO Tutorial

How to get the filepath of a file in Java

In Java, for NIO Path, we can use path.toAbsolutePath() to get the file path; For legacy IO File, we can use file.getAbsolutePath() to get the file path.

For symbolic links or file path contains . or .., we can use path.toRealPath() or file.getCanonicalPath() to get the real file pah.

Below is the mapping of File and Path.

  1. file.getAbsolutePath() <=> path.toAbsolutePath()
  2. file.getCanonicalPath() <=> path.toRealPath()
  3. file.getParent() <=> path.getParent()

1. Get file path of a file (NIO Path).

For java.nio.file.Path, we can use the following APIs to get the file path of a file.

  1. path.toAbsolutePath() – Full file path.
  2. path.toRealPath()) – For symbolic links or resolving the . or .. symbols in the path name, default it follow link.
  3. path.getParent() – Get parent directory of the path.

1.1 Path = /home/mkyong/test/file.txt


Path path = Paths.get("/home/mkyong/test/file.txt");

path                      : /home/mkyong/test/file.txt
path.toAbsolutePath()     : /home/mkyong/test/file.txt
path.getParent()          : /home/mkyong/test
path.toRealPath()         : /home/mkyong/test/file.txt

1.2 Path = file.txt, the file is refer to the current working directory + file.txt.


Path path = Paths.get("file.txt");

path                      : file.txt
path.toAbsolutePath()     : /home/mkyong/projects/core-java/java-io/file.txt
path.getParent()          : null
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/file.txt

1.3 Path = /home/mkyong/test/soft-link, a symbolic link.


$ ln -s
  /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java
  /home/mkyong/test/soft-link

Path path = Paths.get("/home/mkyong/test/soft-link");

path                      : /home/mkyong/test/soft-link
path.toAbsolutePath()     : /home/mkyong/test/soft-link
path.getParent()          : /home/mkyong/test
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java

1.4 Path = /home/mkyong/test/../hello.txt


Path path = Paths.get("/home/mkyong/test/../hello.txt");

path                      : /home/mkyong/test/../hello.txt
path.toAbsolutePath()     : /home/mkyong/test/../hello.txt
path.getParent()          : /home/mkyong/test/..
path.toRealPath()         : /home/mkyong/hello.txt

1.5 Below is a complete Java example to get the file path of different Path.

GetFilePath1.java

package com.mkyong.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetFilePath1 {

    public static void main(String[] args) {

        // full path
        Path path1 = Paths.get("/home/mkyong/test/file.txt");
        System.out.println("\n[Path] : " + path1);
        printPath(path1);

        // file name
        Path path2 = Paths.get("file.txt");
        System.out.println("\n[Path] : " + path2);
        printPath(path2);

        // soft or symbolic link
        Path path3 = Paths.get("/home/mkyong/test/soft-link");
        System.out.println("\n[Path] : " + path3);
        printPath(path3);

        // a path contains `..`
        Path path4 = Paths.get("/home/mkyong/test/../hello.txt");
        System.out.println("\n[Path] : " + path4);
        printPath(path4);

    }

    static void printPath(Path path) {

        System.out.printf("%-25s : %s%n", "path", path);
        System.out.printf("%-25s : %s%n", "path.toAbsolutePath()",
                                                path.toAbsolutePath());
        System.out.printf("%-25s : %s%n", "path.getParent()", path.getParent());
        System.out.printf("%-25s : %s%n", "path.getRoot()", path.getRoot());

        try {

            if (Files.notExists(path)) {
                return;
            }

            // default, follow symbolic link
            System.out.printf("%-25s : %s%n", "path.toRealPath()",
                                                  path.toRealPath());
            // no follow symbolic link
            System.out.printf("%-25s : %s%n", "path.toRealPath(nofollow)",
                path.toRealPath(LinkOption.NOFOLLOW_LINKS));

            // alternative to check isSymbolicLink
            /*if (Files.isSymbolicLink(path)) {
                Path link = Files.readSymbolicLink(path);
                System.out.println(link);
            }*/

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output

Terminal

[Path] : /home/mkyong/test/file.txt
path                      : /home/mkyong/test/file.txt
path.toAbsolutePath()     : /home/mkyong/test/file.txt
path.getParent()          : /home/mkyong/test
path.getRoot()            : /
path.toRealPath()         : /home/mkyong/test/file.txt
path.toRealPath(nofollow) : /home/mkyong/test/file.txt

[Path] : file.txt
path                      : file.txt
path.toAbsolutePath()     : /home/mkyong/projects/core-java/java-io/file.txt
path.getParent()          : null
path.getRoot()            : null
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/file.txt
path.toRealPath(nofollow) : /home/mkyong/projects/core-java/java-io/file.txt

[Path] : /home/mkyong/test/soft-link
path                      : /home/mkyong/test/soft-link
path.toAbsolutePath()     : /home/mkyong/test/soft-link
path.getParent()          : /home/mkyong/test
path.getRoot()            : /
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java
path.toRealPath(nofollow) : /home/mkyong/test/soft-link

[Path] : /home/mkyong/test/../hello.txt
path                      : /home/mkyong/test/../hello.txt
path.toAbsolutePath()     : /home/mkyong/test/../hello.txt
path.getParent()          : /home/mkyong/test/..
path.getRoot()            : /
path.toRealPath()         : /home/mkyong/hello.txt
path.toRealPath(nofollow) : /home/mkyong/hello.txt

2. Get file path of a file (legacy File)

For the legacy IO java.io.File, we can use the following APIs to get the file path of a file.

  1. file.getAbsolutePath() = path.toAbsolutePath()
  2. file.getCanonicalPath() = path.toRealPath()
  3. file.getParent() = path.getParent()
GetFilePath2.java

package com.mkyong.io.howto;

import java.io.File;
import java.io.IOException;

public class GetFilePath2 {

    public static void main(String[] args) {

        // full file path
        File file1 = new File("/home/mkyong/test/file.txt");
        System.out.println("[File] : " + file1);
        printFilePath(file1);

        // a file name
        File file2 = new File("file.txt");
        System.out.println("\n[File] : " + file2);
        printFilePath(file2);

        // a soft or symbolic link
        File file3 = new File("/home/mkyong/test/soft-link");
        System.out.println("\n[File] : " + file3);
        printFilePath(file3);

        // a file contain `..`
        File file4 = new File("/home/mkyong/test/../hello.txt");
        System.out.println("\n[File] : " + file4);
        printFilePath(file4);

    }

    // If a single file name, not full path, the file refer to
    // System.getProperty("user.dir") + file
    static void printFilePath(File file) {
        // print File = print file.getPath()
        System.out.printf("%-25s : %s%n", "file.getPath()", file.getPath());
        System.out.printf("%-25s : %s%n", "file.getAbsolutePath()",
                                              file.getAbsolutePath());
        try {
            System.out.printf("%-25s : %s%n", "file.getCanonicalPath()",
                                                file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.printf("%-25s : %s%n", "Parent Path", getParentPath(file));
    }

    // if unable to get parent, try substring to get the parent folder.
    private static String getParentPath(File file) {
        if (file.getParent() == null) {
            String absolutePath = file.getAbsolutePath();
            return absolutePath.substring(0,
                          absolutePath.lastIndexOf(File.separator));
        } else {
            return file.getParent();
        }
    }

}

Output

Terminal

[File] : /home/mkyong/test/file.txt
file.getPath()            : /home/mkyong/test/file.txt
file.getAbsolutePath()    : /home/mkyong/test/file.txt
file.getCanonicalPath()   : /home/mkyong/test/file.txt
Parent Path               : /home/mkyong/test

[File] : file.txt
file.getPath()            : file.txt
file.getAbsolutePath()    : /home/mkyong/projects/core-java/java-io/file.txt
file.getCanonicalPath()   : /home/mkyong/projects/core-java/java-io/file.txt
Parent Path               : /home/mkyong/projects/core-java/java-io

[File] : /home/mkyong/test/soft-link
file.getPath()            : /home/mkyong/test/soft-link
file.getAbsolutePath()    : /home/mkyong/test/soft-link
file.getCanonicalPath()   : /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java
Parent Path               : /home/mkyong/test

[File] : /home/mkyong/test/../hello.txt
file.getPath()            : /home/mkyong/test/../hello.txt
file.getAbsolutePath()    : /home/mkyong/test/../hello.txt
file.getCanonicalPath()   : /home/mkyong/hello.txt
Parent Path               : /home/mkyong/test/..

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
14 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Totally lost here
6 years ago

WHAT???
“File file = File(“C:\abcfolder\textfile.txt”);
System.out.println(“Path : ” + file.getAbsolutePath());

It will display the full path : “Path : C:\abcfolder\textfile.txt“.
Well, this is EXACTLY what you typed in. IE:you KNEW the path …

liljiji
3 years ago
Reply to  mkyong

And how to get the path of a file if you don’t know the path?

Aaron
11 months ago
Reply to  liljiji

By having the user select their own file from a file picker. This saves you the regex of having to extract the filename from the full path+file name.

Ankit Ostwal
11 years ago

File file = File(“textfile.txt”);

If i only know the name of the file (textfile.txt) as shown above , can i know the whole path of where that file is stored. Bcoz i tried using method file.get absolutePath(). It dosent return the correct path. I am using netbeans IDE.

Phamo
10 years ago
Reply to  Ankit Ostwal

you can try file.getParent()

Areeg
10 years ago
Reply to  Phamo

Thank you of your comment.

Anjani Kumar Jha
8 years ago

Hi,
My requirement is to transfer the excel file from client to server by manually entering the path in text field.
User don’t want the browse button.
When I am entering manually the file path, server(linux) didn’t recognized the path and file not found exception is thrown.

Please let me know how this can be possible.

Ishmael
2 years ago

Images Folder – Using NetBeans IDE 12.x

Save images e.g. ‘Sample.png’ in ‘resources’ folder which will be in the same hierarchy with ‘java’ folder.
(The resources folder contents will be automatically extracted when building the project and sent to a jar file together with compiled classes.)
The jar file will be stored to ‘target’ folder just under the parent project folder.

Next copy all the contents of resources folder manually to the project folder just as files in the project folder.
(these will be used for code testing in the IDE)

For coding image access in the code e.g

img = ImageIO.read(new File(“Sample.png”));

Just type the image filename thats all needed.
Build the project and you will see the images files included with java classes in the “target” folder, in a jar file.
open the jar file to see compiled classes and the images.

Execute the class files normally using java command “java classname”.

To run class files from command line first extract the jar to any location on the computer and cd to that folder.
*** Ensure to copy resources folder contents directly to project folder all the time after updating or replacing resources ***

Any resources outside these folders will require extra code for handling the absolute path for those locations in the computer.

Atfa kanzari
9 years ago

Hi,
How can i get file path from shared folder in Lan?

Thanks in advance

Prasenjit
10 years ago

Is there any any way to get the full path of a file name which has been either stored in internal or external memory??

Thanks in advance

Pathikreet
10 years ago

Hi,

I am relatively new to this so was trying to understand.
I believe the above piece will get the Filewhne it is either placed inside the application or if the code is run on local machine.

But if my code is in some server and i want to get the file from my local machine in the code. How can we do that?