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
?
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
?
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:\
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..
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.
This worked fine for my requirement.
int i = 2;
File filePath;
for(filePath = new File(path); i > 0; filePath = filePath.getParentFile())
i--;