获取文件父文件夹的文件夹名称

我正在使用一些代码,我希望它的行为有所不同,具体取决于文件所在的文件夹名称。我不需要绝对路径只是最终文件夹。 到目前为止,我所看到的一切都是使用文件中指定的绝对路径。

这就是你想要的:

public static String getParentName(File file) { if(file == null || file.isDirectory()) { return null; } String parent = file.getParent(); parent = parent.substring(parent.lastIndexOf("\\") + 1, parent.length()); return parent; } 

遗憾的是,没有预先提供的方法只返回文件路径中最后一个文件夹的名称,因此您必须执行一些字符串操作才能获得它。

我认为java.io.File.getParent()正是你要找的:

 import java.io.File; public class Demo { public static void main(String[] args) { File f = null; String parent="not found"; f = new File("/tmp/test.txt"); parent = f.getParent(); System.out.print("parent name: "+v); } } 

尝试java.io.File.getParentFile()方法。

 String getFileParentName(File file) { if (file != null && file.getParentFile() != null) { return file.getParentFile().getName(); } return null; // no parent for file } 

 String File.getParent() 

还有

 File File.getParentFile() 

我不知道绝对或相对的回报是什么,但如果它是绝对的,你总能找到“\”字符的最后一个(或倒数第二个,依赖的)实例(记得像这样逃避它“ \“)表示最低文件夹级别的位置。

例如,如果函数返回:

“C:\ Users \ YourName”是您最后一次出现“\”的地方,之后的所有字符都是您想要的文件夹

“C:\ Users \ YourName \”是您获得“\”的倒数第二次出现的地方,并且它与最后一个“\”之间的所有字符都将是您要查找的文件夹。

Java File API: http : //docs.oracle.com/javase/7/docs/api/java/io/File.html

 String path = "/abc/def"; // path to the directory try { File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if(file.isDirectory()) { switch(file.getName) { case "folder1" : //do something break case "folder2" : //do something else break } } } } catch(Exception e) { System.out.println("Directory not Found"); }