0

In my program I got a file path E:\MyProject\ImageUploads\TestImageUpload\target\TestImageUpload2\

I need to walk backward and get E:\MyProject\ImageUploads\TestImageUpload

What is the best way to do in java?

Shashika
  • 1,606
  • 6
  • 28
  • 47

4 Answers4

3

Did you mean this?

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

Output:

E:\MyProject\ImageUploads\TestImageUpload\target\TestImageUpload2
E:\MyProject\ImageUploads\TestImageUpload\target
E:\MyProject\ImageUploads\TestImageUpload
E:\MyProject\ImageUploads
E:\MyProject
E:\
  • at times .getparentfile will result in null (e.g. relative path)... so uhm don't think that will do the trick... – witchedwiz Sep 07 '15 at 16:54
  • @witchedwiz what "backward" means is unclear in OP. `new File("..\\..").getParentFile()` is clearly `new File("..")`. –  Sep 07 '15 at 17:03
0

Assuming your image is C:/MyProject/ImageUploads/TestImageUpload/target/TestImageUpload2/someimg.png

apache common utils is your best friend..

enter code here

               FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());

The result is => C:/MyProject/ImageUploads/TestImageUpload/target/TestImageUpload2

then usual drill.. hope it clarifies..

the .getparent() applied on a file created with a likewise parent, otherwise it's a no-no, thus i'd prefer going with filenameutils and that's about that..

witchedwiz
  • 295
  • 2
  • 10
0

Perhaps you could use this:

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

The basic idea is that getAbsoluteFile() will convert the path into an absolute path, and then getParentFile() will find the parent of the named file. You can apply getParentFile() repeatedly (until it returns null) if you want to go through ALL of the parents.

This also works regardless of whether or not the path ends with a slash.

Cel Skeggs
  • 1,827
  • 21
  • 38
0

This worked fine for my requirement.

int i = 2;
File filePath;
for(filePath = new File(path); i > 0; filePath = filePath.getParentFile())
    i--;
Shashika
  • 1,606
  • 6
  • 28
  • 47