How do I get the absolute path of a file in Java?

The following code snippet shows you how to get the absolute path of a file. To do this we use the object getAbsolutePath() method.



public class AbsolutePathExample {
    public static void main(String[] args) {
        // Create an instance of File called file.
        File file = new File("JavaProgrammingBook.pdf");

        // Now we want to know where is exactly this file is
        // located in our file system. To do this we can use
        // the getAbsolutePath() method of the File class.
        String absolutePath = file.getAbsolutePath();

        // Print out the JavaProgrammingBook.pdf location to
        // the console.
        System.out.println("AbsolutePath = " + absolutePath);

Here is the result of the program:

AbsolutePath = /Users/kodejava/Projects/kodejava/JavaProgrammingBook.pdf


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.


  1. I have tried this. but got the path as “E:\Apache Software Foundation\Apache Tomcat 8.0.27\bin\”

Leave a Reply