【问题标题】:Java - shorten the path of a directory [closed]Java - 缩短目录的路径[关闭]
【发布时间】:2012-06-05 09:10:43
【问题描述】:

我想缩短目录的路径。

我知道路径必须从哪个目录开始,例如(路径从1开始):

我想要1\file.txt,而不是C:\temp\top\1\file.txt

【问题讨论】:

  • 使用File.separator而不是反斜杠/斜杠,如果你使用java.io.File,你可以做类似getParent() + getName() 的事情
  • 有什么问题?你试过什么?

标签: java file path directory


【解决方案1】:

注意:小心使用 \ 和 /....

你可以遍历从文件到根目录的路径,检查目录是否是你想要的目录:

File baseDir = new File(basePath);
File candidate = new File(fullPath);
String subPath = candidate.getName();
candidate = candidate.getParent();

while (candidate != null && !candidate.equals(baseDir))
{
    candidate = candidate.getParent();
    subPath = candidate.getName() + File.separatorChar + subPath;
}

// now if candidate == null the file is on another directory, you have to use all the path
// if candidate != null, then subpath has what you want

【讨论】:

    【解决方案2】:

    您可以尝试使用来自String 对象的方法 substring 和 indexOf。

    例子:

    String path = "C:/temp/top/1/file.txt";
    System.out.println(path.substring(path.indexOf("1")));
    

    【讨论】:

    • 也许我的问题弄错了。我认为他/她想从给定自定义文件夹的完整路径中获取相对路径。
    • 投了反对票,没有进一步的解释......
    • 我不是说是你 ;) 正如我所说,我对 OP 想要的东西可能完全错了(虽然我得到了他所说的他想要的东西)但如果我弄错了,我应该得到一个否决我想知道为什么:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2016-03-26
    • 2013-09-04
    • 2023-03-07
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多