[英]Java CharsetDecoder inserting space after every character
我正在嘗試使用此代碼(在Stackoverflow上找到)刪除無效的UTF-8字符:
def text = file.text
CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
ByteBuffer bytes = ByteBuffer.allocate(text.getBytes().length * 2)
CharBuffer cbuf = bytes.asCharBuffer()
cbuf.put(text)
cbuf.flip()
CharBuffer parsed = utf8Decoder.decode(bytes);
println parsed.toString()
我得到的輸出看起來像這樣:
< d o c u m e n t >
< t i t l e > S o me T i t l e < / t i t l e >
< s i t e > A S i t e < / s i t e >
關於它為何如此表現的任何想法?
不知道為什么這不起作用,但這是修復它的代碼(代碼在Groovy中,而不是Java):
file.withInputStream { stream ->
CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
def reader = new BufferedReader(new InputStreamReader(stream, utf8Decoder))
def line = null
def sb = new StringBuilder()
while ( (line = reader.readLine()) != null) {
sb.append("$line\n")
}
reader.close()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.