Home » Java programming language

Java File Class String getPath() method with Example

Java File Class String getPath() method: Here, we are going to learn about the String getPath() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 11, 2019

File Class String getPath()

  • This method is available in package java.io.File.getPath().
  • This method is used to return the path of the file object.
  • The return type of this method is String so it returns the path of the file object in a string form.
  • In this method, it returns the complete path if we don't mention the complete path in the file object.
  • This method does not throw an exception.

Syntax:

    String getPath(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is String so it returns the path of the file object as a String.

Java program to demonstrate example of getPath() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise an 
// exception when working with files
import java.lang.Exception;

public class GetPath {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes to 
            // escape '\' character sequence for windows otherwise 
            // it will be considerable as url.
            File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt");
            File file2 = new File("java.txt");

            // By using getPath() return the path of the file object .
            String path1 = file1.getPath();

            // Display path of the file object if given path is complete.
            System.out.println("The path of the file 1 if given path is complete :" + " " + path1);

            // By using getPath() return the path of the File object 
            // even we have not given [i.e.(java.txt) ]

            String path2 = file2.getPath();

            // Display path of the file object if given path is not absolute.
            System.out.println("The path of the file2 if given path is not absolute :" + " " + path2);

        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

D:\Programs>javac GetPath.java

D:\Programs>java GetPath
The path of the file 1 if given path is absolute : C:\Users\computer clinic\OneDrive\myjava.txt
The path of the file2 if given path is not absolute : D:\Programs\java.txt


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.