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

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

    Here is the code I use:

    public static String sanitizeName( String name ) {
        if( null == name ) {
            return "";
        }
    
        if( SystemUtils.IS_OS_LINUX ) {
            return name.replaceAll( "[\u0000/]+", "" ).trim();
        }
    
        return name.replaceAll( "[\u0000-\u001f<>:\"/\\\\|?*\u007f]+", "" ).trim();
    }
    

    SystemUtils is from Apache commons-lang3

提交回复
热议问题