Is there a cross-platform Java method to remove filename special chars?

后端 未结 8 1580
太阳男子
太阳男子 2021-01-31 13:26

I\'m making a cross-platform application that renames files based on data retrieved online. I\'d like to sanitize the Strings I took from a web API for the current platform.

8条回答
  •  借酒劲吻你
    2021-01-31 14:06

    This is based on the accepted answer by Sarel Botha which works fine as long as you don't encounter any characters outside of the Basic Multilingual Plane. If you need full Unicode support (and who doesn't?) use this code instead which is Unicode safe:

    public class FileNameCleaner {
      final static int[] illegalChars = {34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47};
    
      static {
        Arrays.sort(illegalChars);
      }
    
      public static String cleanFileName(String badFileName) {
        StringBuilder cleanName = new StringBuilder();
        int len = badFileName.codePointCount(0, badFileName.length());
        for (int i=0; i

    Key changes here:

    • Use codePointCount i.c.w. length instead of just length
    • use codePointAt instead of charAt
    • use appendCodePoint instead of append
    • No need to cast chars to ints. In fact, you should never deal with chars as they are basically broken for anything outside the BMP.

提交回复
热议问题