在文件路径中向后走

时间:2015-09-07 16:43:03

标签: java

在我的程序中,我得到了一个文件路径E:\MyProject\ImageUploads\TestImageUpload\target\TestImageUpload2\

我需要向后走,得到E:\MyProject\ImageUploads\TestImageUpload

java中最好的方法是什么?

5 个答案:

答案 0 :(得分:3)

你的意思是?

for(File file = new File("E:\\MyProject\\ImageUploads\\TestImageUpload\\target\\TestImageUpload2\\"); file != null; file = file.getParentFile())
    System.out.println(file);

输出:

E:\MyProject\ImageUploads\TestImageUpload\target\TestImageUpload2
E:\MyProject\ImageUploads\TestImageUpload\target
E:\MyProject\ImageUploads\TestImageUpload
E:\MyProject\ImageUploads
E:\MyProject
E:\

答案 1 :(得分:0)

假设你的形象是 C:/MyProject/ImageUploads/TestImageUpload/target/TestImageUpload2/someimg.png

apache common utils是你最好的朋友..

enter code here

               FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());

结果是=> C:/ MyProject的/ ImageUploads / TestImageUpload /目标/ TestImageUpload2

然后平常钻... 希望它澄清..

.getparent()应用于使用同一个父级创建的文件,否则它是“不 - 不”,因此我更喜欢使用filenameutils并且关于那个...

答案 2 :(得分:0)

也许你可以使用它:

new File("E:\\MyProject\\ImageUploads\\TestImageUpload\\target\\TestImageUpload2\\")
    .getAbsoluteFile().getParentFile()

基本思想是getAbsoluteFile()将路径转换为绝对路径,然后getParentFile()将找到指定文件的父级。如果你想要通过所有父母,你可以反复申请getParentFile()(直到它返回null)。

无论路径是否以斜线结尾,这都有效。

答案 3 :(得分:0)

这符合我的要求。

int i = 2;
File filePath;
for(filePath = new File(path); i > 0; filePath = filePath.getParentFile())
    i--;

答案 4 :(得分:-1)

你只需要把“../”这两个点向后跳

相关问题