gpt4 book ai didi

java - Java中的垃圾字符删除

转载 作者:可可西里 更新时间:2023-11-01 06:30:34 26 4
gpt4 key购买 nike

在文本字段中,如果我从 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”。

最佳答案

您必须交换编码和解码调用。 加上;你正在解码两次,只有一种编码!

你写道:

CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(bufferToConvert));
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(cbuf));
userText = decoder.decode(bbuf).toString();

但是,显然,它必须是:

ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(userText));
CharBuffer cbuf = decoder.decode(bbuf);
userText = cbuf.toString();

首先,您必须对文本进行编码,然后对编码结果进行解码。

关于java - Java中的垃圾字符删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11628502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com