您的位置 首页 java

Java 文件路径和URL路径规则化

1、工具类

 import  java .io. File ;
import java.util. regex .Matcher;

public class Helper {
    // 正则化文件路径
    public  static  String normalizePath(String path) {
        String result = path.replaceAll("/+", Matcher.quoteReplacement(File.separator));
        return result.replaceAll("\\\\+", Matcher.quoteReplacement(File.separator));
    }
  
    // 正则化URL路径
    public static String normalizeUrl(String path) {
        String placeholder = "6445BF55-95C4-41F9-8235-34CE3ED9146D";
        String result = path.replaceAll("\\\\+", "/");
        result = result.replaceAll("/+", "/");
        result = result.replaceAll("http:/+", placeholder);
        return result.replace(placeholder, "#34;);
    }
}  

2、测试类

 public class Application {
    public static  void  main(String[] args) throws  Exception  {
        String path = "d:/\\\\\\\\/\\//abc\\/\\\\\\defced";
        String normalizePath = Helper.normalizePath(path);
        System.out.println(normalizePath);

        String url = "http:/\\\\\\\\\\\\///localhost:2020/roleaddd\\\\\\show\\\\\\\\\\aaa";
        String normalizeUrl = Helper.normalizeUrl(url);
        System.out.println(normalizeUrl);
    }
}  

如果您有什么好的想法与方法,欢迎评论区留言,我们一起讨论~

文章来源:智云一二三科技

文章标题:Java 文件路径和URL路径规则化

文章地址:https://www.zhihuclub.com/173928.shtml

关于作者: 智云科技

热门文章

网站地图