Adding actual quotation marks is only a small part of the problem; as soon as you do this, you are likely to run into a real problem: what happens if the line already contains quotation marks or lines or other non-printable characters?
The following method will take care of everything:
public static String escapeForJava( String value, boolean quote ) { StringBuilder builder = new StringBuilder(); if( quote ) builder.append( "\"" ); for( char c : value.toCharArray() ) { if( c == '\'' ) builder.append( "\\'" ); else if ( c == '\"' ) builder.append( "\\\"" ); else if( c == '\r' ) builder.append( "\\r" ); else if( c == '\n' ) builder.append( "\\n" ); else if( c == '\t' ) builder.append( "\\t" ); else if( c < 32 || c >= 127 ) builder.append( String.format( "\\u%04x", (int)c ) ); else builder.append( c ); } if( quote ) builder.append( "\"" ); return builder.toString(); }
Mike Nakis Mar 16 '15 at 8:33 2015-03-16 08:33
source share