public static String escape(String str) {
        int len = str.length();
        StringBuffer buf = new StringBuffer(len + 5);
        char[] ch = str.toCharArray();
    
        for (int i = 0; i < len; i++) {
            switch (ch[i]) {
            case '\\' :
                buf.append("\\\\");
                break;
            case '\n' :
                buf.append("\\n");
                break;
            case '\r' :
                buf.append("\\r");
                break;
            case '\t' :
                buf.append("\\t");
                break;
            case '\b' :
                buf.append("\\b");
                break;
            case '"' :
                buf.append("\\\"");
                break;
            default :
                buf.append(ch[i]);
            }
        }
    
        return '"' + buf.toString() + '"';
    }