public static String toSafeFileName ( String name ) { int size = name . length ( ) ; StringBuilder builder = new StringBuilder ( size * 2 ) ; for ( int i = 0 ; i < size ; i ++ ) { char c = name . charAt ( i ) ; boolean valid = c >= ' ' && c <= ' ' ; valid = valid || ( c >= ' ' && c <= ' ' ) ; valid = valid || ( c >= ' ' && c <= ' ' ) ; valid = valid || ( c == ' ' ) || ( c == ' ' ) || ( c == ' ' ) ; if ( valid ) { builder . append ( c ) ; } else { // Encode the character using hex notation builder . append ( ' ' ) ; builder . append ( Integer . toHexString ( i ) ) ; } } return builder . toString ( ) ; }
Converts any string into a string that is safe to use as a file name . The result will only include ascii characters and numbers and the - _ and . characters .