How can I safely encode a string in Java to use as a filename?

后端 未结 9 2017
失恋的感觉
失恋的感觉 2020-11-29 22:53

I\'m receiving a string from an external process. I want to use that String to make a filename, and then write to that file. Here\'s my code snippet to do this:



        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 23:23

    This is probably not the most effective way, but shows how to do it using Java 8 pipelines:

    private static String sanitizeFileName(String name) {
        return name
                .chars()
                .mapToObj(i -> (char) i)
                .map(c -> Character.isWhitespace(c) ? '_' : c)
                .filter(c -> Character.isLetterOrDigit(c) || c == '-' || c == '_')
                .map(String::valueOf)
                .collect(Collectors.joining());
    }
    

    The solution could be improved by creating custom collector which uses StringBuilder, so you do not have to cast each light-weight character to a heavy-weight string.

提交回复
热议问题