Quoted-printable qp符号化実装、vcfエクスポートで使用
5329 ワード
package com.chinaGPS.driverBook.util;
import java.io.ByteArrayOutputStream;
/**Qp
* @author zhz
*
*/
public class QpEncodeUtil {
/**
* quoted-printable
*/
public static String qpEncodeing(String str) {
return qpEncodeing(str, "UTF-8");
}
/**
* quoted-printable
*
* @param str
* @return
*/
public static String qpDecoding(String str) {
return qpDecoding(str, "UTF-8");
}
/**
* quoted-printable
* @param str
* @param charsetName
* @return
*/
private static String qpEncodeing(String str, String charsetName) {
char[] encode = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < encode.length; i++) {
if ((encode[i] >= '!') && (encode[i] <= '~') && (encode[i] != '=')
&& (encode[i] != '
')) {
sb.append(encode[i]);
} else if (encode[i] == '=') {
sb.append("=3D");
} else if (encode[i] == '
') {
sb.append("/n");
} else {
StringBuffer sbother = new StringBuffer();
sbother.append(encode[i]);
String ss = sbother.toString();
byte[] buf = null;
try {
buf = ss.getBytes(charsetName);
}
catch (Exception e) {
e.printStackTrace();
}
//UTF-8: buf.length == 3
//GBK: buf.length == 2
if (buf.length == 3 || buf.length == 2) {
for (int j = 0; j < buf.length; j++) {
String s16 = String.valueOf(Integer.toHexString(buf[j]));
// 16 , =E8 ,
//
char c16_6;
char c16_7;
if (s16.charAt(6) >= 97 && s16.charAt(6) <= 122) {
c16_6 = (char) (s16.charAt(6) - 32);
} else {
c16_6 = s16.charAt(6);
}
if (s16.charAt(7) >= 97 && s16.charAt(7) <= 122) {
c16_7 = (char) (s16.charAt(7) - 32);
} else {
c16_7 = s16.charAt(7);
}
sb.append("=" + c16_6 + c16_7);
}
}
}
}
return sb.toString();
}
private static String qpDecoding(String str, String charsetName) {
if (str == null) {
return "";
}
try {
StringBuffer sb = new StringBuffer(str);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == ' ' && sb.charAt(i - 1) == '=') {
//
// sb.deleteCharAt(i);
sb.deleteCharAt(i - 1);
}
}
str = sb.toString();
byte[] bytes = str.getBytes("US-ASCII");
if (bytes == null) {
return "";
}
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (b != 95) {
bytes[i] = b;
} else {
bytes[i] = 32;
}
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i];
if (b == '=') {
try {
int u = Character.digit((char) bytes[++i], 16);
int l = Character.digit((char) bytes[++i], 16);
if (u == -1 || l == -1) {
continue;
}
buffer.write((char) ((u << 4) + l));
}
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
} else {
buffer.write(b);
}
}
return new String(buffer.toByteArray(), charsetName);
}
catch (Exception e) {
e.printStackTrace();
return "";
}
}
}