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

后端 未结 8 1670
太阳男子
太阳男子 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:13

    There's a pretty good built-in Java solution - Character.isXxx().

    Try Character.isJavaIdentifierPart(c):

    String name = "name.é+!@#$%^&*(){}][/=?+-_\\|;:`~!'\",<>";
    StringBuilder filename = new StringBuilder();
    
    for (char c : name.toCharArray()) {
      if (c=='.' || Character.isJavaIdentifierPart(c)) {
        filename.append(c);
      }
    }
    

    Result is "name.é$_".

提交回复
热议问题