Java 过滤上传文件名的特殊字符方法

 public static void main(String[] args) throws UnsupportedEncodingException {
        String name= "test%dasda da&sda  s / \\ \" : | * ? < >.mp4";
       /* System.out.println(name.replaceAll("\\s*",""));

        System.out.println(FilenameUtils.getPrefix(name));*/

        Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
        Matcher matcher = pattern.matcher(name);

        String name1 = matcher.replaceAll("");

        String name2 = name.replaceAll("[\\s\\\\/:\\*\\?\\\"<>\\|]","");

        // 使用Spring提供的工具类UriUtils      
        String name3 = UriUtils.encode(name,"UTF-8");

        System.out.println(name1);

        System.out.println("------------");

        System.out.println(name2);

        System.out.println("------------");

        System.out.println(name3);
    }

结果:

test%dasdada&sdas.mp4
------------
test%dasdada&sdas.mp4
------------
test%25dasda%20da%26sda%20%20s%20%2F%20%5C%20%22%20%3A%20%7C%20%2A%20%3F%20%3C%20%3E.mp4

推荐使用第二种

你可能感兴趣的:(java,文件名)