public static String javaEncode(String s){
  int length=s.length();
  StringBuilder buff=new StringBuilder(length);
  for (int i=0; i < length; i++) {
    char c=s.charAt(i);
switch (c) {
case '\t':
      buff.append("\\t");
    break;
case '\n':
  buff.append("\\n");
break;
case '\f':
buff.append("\\f");
break;
case '\r':
buff.append("\\r");
break;
case '"':
buff.append("\\\"");
break;
case '\\':
buff.append("\\\\");
break;
default :
int ch=c & 0xffff;
if (ch >= ' ' && (ch < 0x80)) {
buff.append(c);
}
 else {
buff.append("\\u");
String hex=Integer.toHexString(ch);
for (int len=hex.length(); len < 4; len++) {
buff.append('0');
}
buff.append(hex);
}
}
}
return buff.toString();
}

public static String javaEncode ( String s ) { int length = s . length ( ) ; StringBuilder buff = new StringBuilder ( length ) ; for ( int i = 0 ; i < length ; i ++ ) { char c = s . charAt ( i ) ; switch ( c ) { case '\t' : buff . append ( "\\t" ) ; break ; case '\n' : buff . append ( "\\n" ) ; break ; case '\f' : buff . append ( "\\f" ) ; break ; case '\r' : buff . append ( "\\r" ) ; break ; case '"' : buff . append ( "\\\"" ) ; break ; case '\\' : buff . append ( "\\\\" ) ; break ; default : int ch = c & 0xffff ; if ( ch >= ' ' && ( ch < 0x80 ) ) { buff . append ( c ) ; } else { buff . append ( "\\u" ) ; String hex = Integer . toHexString ( ch ) ; for ( int len = hex . length ( ) ; len < 4 ; len ++ ) { buff . append ( '0' ) ; } buff . append ( hex ) ; } } } return buff . toString ( ) ; }
convert a string to a java literal using the correct escape sequences . the literal is not enclosed in double quotes . the result can be used in properties files or in java source code .
