Google+

261. Using getPath( ) and getAbsolutePath( ) methods







Pre-requisites -


getPath( ) gives the relative path that is specified in the File Class object creation statement. For example, if we have specified the file name say 'fileX.txt' in the File Class object creation statement, the getPath( ) method method will return the relative path (i.e. the path that we have provided in the object creation statement) 'fileX.txt' as shown in the below example -

//Assuming that 'fileX.txt' is available in your Project Workspace.

File file1 = new File("fileX.txt"); 

System.out.println(file1.getPath( ));

Output -

fileX.txt



Where as getAbsolutePath( ) will give the complete path of the 'fileX.txt' in your workspace as shown in the below example -

File file1 = new File("fileX.txt");

System.out.println(file1.getAbsolutePath( ));

Output -

E:\Selenium\Selenium Projects\Project 50

Hence we can use getPath( ) to get the relative path and getAbsolutePath( ) to get the complete path of the file in our Project Workspace.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Class 'GetRelativeAndAbsolutePaths.java' with main( ) method in the existing Java Project 'Project 50' as shown below -



2. Go to your Projects workspace and right click to create a new text file as shown below -


3. Name the file as 'fileX' as shown below -

4. In Eclipse IDE, create a File Class object for the above created text file as shown below (Resolve the import errors) -




5. There is no need of creating a file 'fileX.txt' using the createNewFile( ) method, as we have manually created that in our Project Workspace. Now lets find the relative path and absolute paths using getPath( ) and getAbsolutePath( ) methods and print the retrieved paths using the print statements as shown below -



6. Save & Run the Java Class 'GetRelativeAndAbsolutePaths.java' and observe that the required paths of fileX.txt file got printed in the output as shown below -


Hence the relative path 'fileX.txt' is given by the getPath( ) method and the absolute path 'E:\Selenium\Selenium Projects\Project 50\fileX.txt' is given by the getAbsolutePath( ) method.







Please comment below to feedback or ask questions.

Using exists( ) method will be explained in the next post.










No comments: