Java 在文件路径中向后走
在我的程序中,我得到了一个文件路径Java 在文件路径中向后走,java,Java,在我的程序中,我得到了一个文件路径E:\MyProject\ImageUploads\TestImageUpload\target\TestImageUpload2\ 我需要向后走,并获得E:\MyProject\ImageUploads\TestImageUpload 在java中最好的方法是什么?你是说这个吗 for(File file = new File("E:\\MyProject\\ImageUploads\\TestImageUpload\\target\\TestImageUpl
E:\MyProject\ImageUploads\TestImageUpload\target\TestImageUpload2\
我需要向后走,并获得E:\MyProject\ImageUploads\TestImageUpload
在java
中最好的方法是什么?你是说这个吗
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:\
假设你的形象是
C:/MyProject/ImageUploads/TestImageUpload/target/TestImageUpload2/someimg.png
apache common utils是您最好的朋友
enter code here
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
结果是=>C:/MyProject/ImageUploads/TestImageUpload/target/TestImageUpload2
然后是通常的训练。。
希望它能澄清
.getparent()应用于使用类似父级创建的文件,否则它是否定的,因此我更喜欢使用filenameutils,仅此而已。也许您可以使用以下方法:
new File("E:\\MyProject\\ImageUploads\\TestImageUpload\\target\\TestImageUpload2\\")
.getAbsoluteFile().getParentFile()
基本思想是getAbsoluteFile()
将路径转换为绝对路径,然后getParentFile()
将找到命名文件的父级。如果要遍历所有父级,可以重复应用getParentFile()
(直到返回null)
无论路径是否以斜杠结束,这也可以使用。这很适合我的要求
int i = 2;
File filePath;
for(filePath = new File(path); i > 0; filePath = filePath.getParentFile())
i--;
你只需要把“./”这两个点向后跳可能的重复项否,我没有从它那里得到一个解决方案,重复项可能通过“\`删除最后两个元素来分割文件路径字符串,它会起作用,我想有时在Java中有更好的方法来做。getparentfile将导致null(例如相对路径)。。。所以,嗯,我不认为这会起作用…@witchedwiz“backward”的意思在OP.
新文件(“…\\”)中不清楚。getParentFile()
显然是新文件(“…”)
。用户正在从编程的角度寻找答案。@AnkitTanna,再次阅读他的问题