List<String> path = Arrays.asList(Paths.get("").toAbsolutePath().toString().split("\\\\"));
System.out.println(path);
int removeJavaFile = path.size() - 1;
path.remove(removeJavaFile);
String filePath = path.stream().map(n -> String.valueOf(n)).collect(Collectors.joining("\\\\"));
System.out.println(filePath);
I was trying to get the directory in which my program is, and ended up using this to get the path to the file. I thought of getting the path, and then splitting it to later remove the file name from the path to get the directory, but failed to do so, despite using the .remove()
method. Could anyone please help me out?
pathToFile.getParent()
Path#getParent
No need to resort to crude string manipulation. Java NIO abstracts us away from the platform-specific details.
Call Path#getParent
to get another path object while dropping the last element of the original.
Path pathToFile = Paths.get( "SomeFolder" , "SomeFile" ) ;
Path pathToFolder = pathToFile.getParent() ;
List#removeLast
By the way, to answer the title of your Question…
In Java 21+, List
is a sub-interface of SequencedCollection
. This brings convenient new methods such as removeLast.
myList.removeLast() ;