当我从Word复制到文本字段中时,会插入垃圾字符。在从JSP页面发布参数时,它仍然正常。但是,在Java中获取参数时,它会转换为垃圾字符。我使用了以下代码在插入之前消除垃圾字符。我正在使用MySQL数据库。(JBOSS 5.1 GA服务器)
String outputEncoding = "UTF-8";
Charset charsetOutput = Charset.forName(outputEncoding);
CharsetEncoder encoder = charsetOutput.newEncoder();
byte[] bufferToConvert = userText.getBytes();
CharsetDecoder decoder = (CharsetDecoder) charsetOutput.newDecoder();
try {
CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(bufferToConvert));
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(cbuf));
userText = decoder.decode(bbuf).toString();
} catch (CharacterCodingException e) {
e.printStackTrace();
}
但是当我使用单引号('')和双引号("")时,仍然会得到垃圾字符。我需要使用UTF-8编码的字符串。有人能建议我哪里出了问题吗?
举例:输入 - "esgh"。 输出 - â??esghâ?? : 期望输出 - "esgh"。
inputDecoder
变量。这是有意为之还是错误?我认为您应该针对此输入字符类型获取一个Charset
实例,并使用它来代替从输出字符集获取的解码器。 - Duncan Jones