Path

2 0 0
                                        

Path - is the location of your file in your directory.

Absolute Path - complete path direction which includes the root directory like drive c or drive d.

relative path - need to be combine to another path to be access.

sample:

c:/home/folder1/subfolder/YourDocument.txt


symbolic link - this a file where it is connected to another file that is on a separate path.


Path class - it is a class where you can locate a file in file system. Locate only and not access a file. Take note of the double back slash since a single backslash is used in escape characters like

for newline.


String direction = "C:\\Folder1\\Subfolder\\AnotherSubfolder\\YourFile";

syntax 1:

Path objectName = Paths.get(direction);


syntax 2:

Path objectName = FileSystems.getDefault().getPath(direction);


syntax 3:

Path objectName1 = Path.of("YourFile");

Path objecName2 = objectName1.resolve("C:\\Folder1\\SubFolder\\AnotherSubfolder");


syntax 4:

String prop = System.getProperty("C:");       //THIS RETURNS A NULL. DON'T KNOW WHY

String yourDirection = prop + "\\Folder1"\\Subfolder\\AnotherSubfolder\\YourFile";

Path objectName = Paths.get(yourDirection);


syntax 5: (USING TWO DOTS .. TO OMIT PARENT'S NAME)

String yourDirection = "C:\\..YourFile";

Path objectName = Paths.get(yourDirection); //THIS WAS TREATED AS ABSOLUTE


syntax 6:

Path path = Path.of("YourFile");

Path objectName = path.toRealPath(); 

//THIS RETURNS AN ABSOLUTE PATH. YOU CAN DO path.toAbsolutePath() TOO. IT WORKS THE SAME


=====================

class PracticingPath{

    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a file name below:");

        String direction = scanner.nextLine();

        Path path = Path.of(direction);

        Path path2 = path.toAbsolute();

        if(path2.isAbsolute()){

            System.out.println("Your path: " + path2.getParent());

        }else {

            System.out.println("Path is not absolute!");

        }

        scanner.close();

    }

}

====================

Result:

YourFile.txt

Your path: C:\\Folder1\\Subfolder\\AnotherSubfolder\\YourFile


Note: There are other usefult methods in here. You can do some dora exploration in here.


Java ProgrammingWhere stories live. Discover now