If i have a String that contains a path like
"D:\Folder\Folder2\file.txt"
, how can i remove the file and have only
"D:\Folder\Folder2"
Thank you for your time. :D
If i have a String that contains a path like
"D:\Folder\Folder2\file.txt"
, how can i remove the file and have only
"D:\Folder\Folder2"
Thank you for your time. :D
You could use the Apaches FilenameUtils..
This class defines six components within a filename (example
C:\dev\project\file.txt):
the prefix - C:\
the path - dev\project\
the full path -> C:\dev\project\
the name - file.txt
the base name - file
the extension - txt
So by using following code, you get the full path (without the filename):
getFullPath("D:\\Folder\\Folder2\\file.txt");
Please have a look at https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html
Java IO and NIO packages has classes for file handling - File
and Path
. All of these do same job to extract parent as Path, File or String and avoid hardcoding file separator:
import java.io.File:
File parent = new File("D:\\Folder\\Folder2\\file.txt").getParentFile();
String parent = new File("D:\\Folder\\Folder2\\file.txt").getParent();
import java.nio.file.Path:
Path parent = Path.of("D:\\Folder\\Folder2\\file.txt").getParent();
String parent = Path.of("D:\\Folder\\Folder2\\file.txt").getParent().toString();
String a = "D:\\Folder\\Folder2\\file.txt";
System.out.print(a.substring(0, a.lastIndexOf("\\")));