Here you can find the source of escapeJavaString(String str)
public static String escapeJavaString(String str)
//package com.java2s; /*// w w w . java 2s .com Copyright 2016 Goldman Sachs. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.util.*; public class Main { public static String escapeJavaString(String str) { StringBuilder builder = new StringBuilder(str.length()); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { builder.append("\\u" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else if (ch > 0xff) { builder.append("\\u0" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else if (ch > 0x7f) { builder.append("\\u00" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else if (ch < 32) { switch (ch) { case '\b': builder.append('\\'); builder.append('b'); break; case '\n': builder.append('\\'); builder.append('n'); break; case '\t': builder.append('\\'); builder.append('t'); break; case '\f': builder.append('\\'); builder.append('f'); break; case '\r': builder.append('\\'); builder.append('r'); break; default: if (ch > 0xf) { builder.append("\\u00" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else { builder.append("\\u000" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } break; } } else { switch (ch) { case '"': builder.append('\\'); builder.append('"'); break; case '\\': builder.append('\\'); builder.append('\\'); break; default: builder.append(ch); break; } } } return builder.toString(); } }