Java File getPath() method with examples

January 04, 2020 No comments Java IO Examples File getPath

1. Introduction

The getPath() method returns string representation of the file path. Returned string uses File.separator - system-dependent default name-separator character (in Windows \\ in Unix / character) to separate the file and directory names.

2. Method signature

public String getPath()

Parameters:

  • method does not take any parameter

Returns

  • String - path to the file or directory

3. Examples

3.1. The program that returns paths of given file and directory

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/frontbackend.txt");
            File dir = new File("/tmp/frontbackend");

            System.out.println(file.getPath()); // /tmp/frontbackend.txt

            System.out.println(dir.getPath()); // /tmp/frontbackend

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

The output:

/tmp/frontbackend.txt
/tmp/frontbackend

4. Conclusion

In this article, we presented File.getPath() method that returns the system-dependent path to the file or directory. The method used default system separator to separate the individual path components.

{{ message }}

{{ 'Comments are closed.' | trans }}