Shkumbin Delija Shkumbin Delija - 3 months ago 8
Java Question

How to get the path of a file but without the actual file name

For example

C:\Desktop
and not
C:\Desktop\file.txt
.
Here's the code, what can i do to get only the path excluding the actual name of the file or do i have to mechanically remove the name part(String) with the
split("\")
method.

import java.io.*;

public class FilesInfo {

File file = new File("C:\\Users\\CCKS\\Desktop\\1");

public void viewFiles() throws IOException {
File[] files = file.listFiles();
String path = "";

for(int i = 0; i < files.length; i++){
if(!files[i].isDirectory()){
System.out.println("[DIRECTORY]" + files[i].getPath() + " [NAME] " + files[i].toString() + " [SIZE] " + files[i].length() + "KB");
} else {
path = files[i].getAbsolutePath();
file = new File(path);
}
}

if(path.equals("")){
return;
} else {
viewFiles();
}
}

public static void main(String [] args){
try {
new FilesInfo().viewFiles();
} catch (Exception e){
e.printStackTrace();
}

}
}

Answer

Like this,

File file = new File("C:\Desktop\file.txt");
String parentPath= file.getParent();