-2

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

  • Hint: You can use String's `substring` and `lastIndexOf` methods – Thiyagu Jan 04 '21 at 06:19
  • 2
    Does this answer your question? [How do I get the file name from a String containing the Absolute file path?](https://stackoverflow.com/questions/14526260/how-do-i-get-the-file-name-from-a-string-containing-the-absolute-file-path) – fdermishin Jan 04 '21 at 06:53

3 Answers3

0

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

sefrie
  • 48
  • 6
0

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();
DuncG
  • 12,137
  • 2
  • 21
  • 33
-1
String a = "D:\\Folder\\Folder2\\file.txt";
System.out.print(a.substring(0, a.lastIndexOf("\\")));
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43