javafilepathapache-commons

Java, get full path of file and removing filename


I'm trying to get the directory path to a file. The issue I am having is getting the last \ or / of the directory. As this code is supposed to work on all operating systems, I can't seem to find any solution for this. Any help is appreciated.

My code so far:

System.out.print("Enter dir: ");
String path = kb.nextLine();
File pathes = new File(path);
String path2 = pathes.getParent();
path = path.substring(0, path.lastIndexOf("\\")+1);
System.out.println("PATH: " + path);
System.out.println("PATH2: "+path2);

My output is:

PATH: C:\Users\User\Desktop\test\
PATH2: C:\Users\User\Desktop\test

This is just test code and not the real code I'm working on.

EDIT What I'm trying to get is

C:\Users\User\Desktop\test\

from

C:\Users\User\Desktop\test\test.txt

Solution

  • To get the absolute path to the parent directory you can do:

    File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt");
    String path = f.getParentFile().getAbsolutePath();
    System.out.println(path);
    

    Output:

    C:\Users\User\Desktop\test
    

    If you really want the trailing slash, then you can just append File.separator:

    File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt ");
    String path = f.getParentFile().getAbsolutePath() + File.separator;
    System.out.println(path);
    

    Output:

    C:\Users\User\Desktop\test\