【问题标题】:How to get the path from a file URL?如何从文件 URL 中获取路径?
【发布时间】:2011-11-06 15:24:45
【问题描述】:

我有这种格式的字符串:

file://c:/Users/....
file://E:/Windows/....
file:///f:/temp/....
file:///H:/something/....

我怎样才能只得到c:/Users/...H:/something/...

【问题讨论】:

    标签: java regex indexing substring


    【解决方案1】:

    经过测试,将替换任意数量的斜线。

    String path = yourString.replaceFirst("file:/*", "");
    

    如果你只希望它匹配两个或三个斜杠

    String path = yourString.replaceFirst("file:/{2,3}", "");
    

    【讨论】:

    • [] 是多余的。此外,///?/{2,3} 更短更简单。
    【解决方案2】:
    String path = new java.net.URI(fileUrl).getPath();
    

    【讨论】:

      【解决方案3】:

      您可以将字符串中的字符串“file://”替换为空:

      String path = yourString.replace("file://", "");
      

      【讨论】:

      • 如果它包含 3 个像 file:/// 这样的斜线呢?
      • 上述答案将不满足 file:///f:/temp/.... file:///H:/something/....
      • String path = yourString.replaceFirst("^file:///?", ""); - 没有方法String.replace(String, String)
      • @Christoffer Hammarström :那file://c/Users
      【解决方案4】:

      那又怎样?

      String path = yourString.replaceFirst("file:[/]*", "");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        • 1970-01-01
        • 2012-01-19
        • 1970-01-01
        • 1970-01-01
        • 2021-03-27
        相关资源
        最近更新 更多