File and Folder path operations in java. Many time while working with java we need to access the path of a file or the path of any folder so in this complete tutorial will see some examples to play with the system path. Let’s see examples one by one.
How to read folder name of a file in Java
getParent() method is used to get the path of a folder it will return the exact path of the folder where the file exists. For example, we have one file called “demo.docs” and it’s in the “Articles” folder then it will return the path of the “Articles” folder.
File f = new File("F:\\Articles\\Demo.docs"); System.out.println("=====Folder Path of the file====="); System.out.println(f.getParent());
How to read file name in Java
getName() method is used to get the file name in java. It will return the exact name of the file. For Example, My file name is “Demo.docs” then it will return “Demo.docs”.
File f = new File("F:\\Articles\\Demo.docs"); System.out.println("=====Name of the file====="); System.out.println(f.getName());
How to read the path of a file in Java
getCanonicalPath() method will return the exact path of a file from the root folder to file name.
File f = new File("F:\\Articles\\Demo.docs"); System.out.println("=====Path of the file====="); System.out.println(f.getCanonicalPath());
How to find the dynamic path of the working directory in Java
System.getProperty(“user.dir”) is used to get the path of the current working directory in Java.
System.out.println("=====Path of the current working Directory====="); System.out.println(System.getProperty("user.dir"));
Code to Find File Path || Folder Path || Current working directory in Java
package com.demo.app.model; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { File f = new File("F:\\Articles\\Demo.docs"); System.out.println("=====Folder Path of the file====="); System.out.println(f.getParent());// /home/jigar/Desktop System.out.println("=====Name of the file====="); System.out.println(f.getName()); try { System.out.println("=====Path of the file====="); System.out.println(f.getCanonicalPath()); System.out.println("=====Path of the current working Directory====="); System.out.println(System.getProperty("user.dir")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Output: