问题给你解决了,看代码
public class Test {
public static void main(String[] args) {
try {
String s = new String("中文测试局部乱码问题2011中文测试上传文件名乱码问题.txt".getBytes(),
"UTF-8");
System.out.println(s);
s = java.net.URLDecoder.decode(s, "utf-8"); //utf8转gbk
System.out.println(s);
Test convert = new Test();
byte[] fullByte = convert.gbk2utf8(s); //gbk转utf8
String fullStr = new String(fullByte, "UTF-8");
System.out.println("string from GBK to UTF-8 byte: " + fullStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] gbk2utf8(String chenese) {
char c[] = chenese.toCharArray();
byte[] fullByte = new byte[3 * c.length];
for (int i = 0; i < c.length; i++) {
int m = (int) c[i];
String word = Integer.toBinaryString(m);
StringBuffer sb = new StringBuffer();
int len = 16 - word.length();
for (int j = 0; j < len; j++) {
sb.append("0");
}
sb.append(word);
sb.insert(0, "1110");
sb.insert(8, "10");
sb.insert(16, "10");
String s1 = sb.substring(0, 8);
String s2 = sb.substring(8, 16);
String s3 = sb.substring(16);
byte b0 = Integer.valueOf(s1, 2).byteValue();
byte b1 = Integer.valueOf(s2, 2).byteValue();
byte b2 = Integer.valueOf(s3, 2).byteValue();
byte[] bf = new byte[3];
bf[0] = b0;
fullByte[i * 3] = bf[0];
bf[1] = b1;
fullByte[i * 3 + 1] = bf[1];
bf[2] = b2;
fullByte[i * 3 + 2] = bf[2];
}
return fullByte;
}
}
结果:
中文测试局部乱码问题2011中文测试上传文件名乱码问题.txt
中文测试局部乱码问题2011中文测试上传文件名乱码问题.txt
string from GBK to UTF-8 byte: 中文测试局部乱码问题2011中文测试上传文件名乱码问题.txt
从第一行正确可以看出,你的系统默认编码是UTF-8;
第一行的意思是根据UTF-8解码,然后再编码
所以用什么解码,就需要用什么编码
String s = new String("中文测试局部乱码问题2011中文测试上传文件名乱码问题.txt".getBytes(),"UTF-8");
System.out.println(s);
s = new String(s.getBytes("GBK"), "GBK");
System.out.println(s);
s = new String(s.getBytes("UTF-8"), "UTF-8");
System.out.println(s);
控件上传的是什么编码你查一下嘛,然后直接new String(s.getBytes("控制上传字符串的编码"),"你指定的编码格式") 就好了,tomcat中的表单默认的上传编码格式是ISO-8859-1,直接转成你要的格式:如new String(getRequest().getParameter("content").getBytes("ISO-8859-1"), "UTF-8");