private String createKeyValue ( String key , String value ) { StringBuilder sb = new StringBuilder ( ) ; // no quoting the key; "Keys are alphanumeric strings which may contain periods (.) and hyphens (-)" sb . append ( key ) . append ( ' ' ) ; if ( value == null || value . isEmpty ( ) ) { return sb . append ( "\"\"" ) . toString ( ) ; } StringBuilder valBuf = new StringBuilder ( ) ; boolean toBeQuoted = false ; for ( int i = 0 ; i < value . length ( ) ; ++ i ) { char c = value . charAt ( i ) ; switch ( c ) { case ' ' : case ' ' : case ' ' : // escape the character valBuf . append ( ' ' ) ; case ' ' : // space needs quotes, too toBeQuoted = true ; default : // always append valBuf . append ( c ) ; } } if ( toBeQuoted ) { // need to keep quotes sb . append ( ' ' ) . append ( valBuf . toString ( ) ) . append ( ' ' ) ; } else { sb . append ( value ) ; } return sb . toString ( ) ; }
Escape any slashes quotes and newlines int the value . If any escaping occurred quote the value .