讀取未知編碼的文本行 (Reading lines of text in unknown encoding)


問題描述

讀取未知編碼的文本行 (Reading lines of text in unknown encoding)

I need to read a text file line by line, and apply to each of them several CharsetDecoders, in order. Actually, I first try to decode line as if it's an UTF8-encoded one, and fallback to one-byte charset if UTF8 CharsetDecoder raises MalformedInputException.

However, if I use InputStreamReader with default or specified charset, readLine function silently replaces with '?' all the bytes it thinks are invalid for the specified charset.

I finally ended up writing my own function for reading lines, that reads from a stream byte by byte, seeks for line terminators and constructs lines. But this way it appears terribly slow.

Is there any way to make Java to read lines without touching bytes?

UPDATE: I've found out that there are charsets in which all 256 bytes are valid, two of them line terminators. So it is possible to read raw byte stream line by line. Examples of such charsets are:

IBM00858 IBM437 IBM775 IBM850 IBM852 IBM855 IBM860 IBM861 IBM862 IBM863 IBM865 IBM866 ISO-8859-1 ISO-8859-13 ISO-8859-15 ISO-8859-2 ISO-8859-4 ISO-8859-5 ISO-8859-9 KOI8-R KOI8-U windows-1256

The question is now closed.


參考解法

方法 1:

You can't use a reader class and not expecting it to decode the underlying byte stream. If you have a file where each line is encoded in a different charset (?), then you'd better of devise a method of detecting the underlying character encoding. Perhaps you can use an encoding detector such as juniversalchardet.

(by day7Amin Mozafari)

參考文件

  1. Reading lines of text in unknown encoding (CC BY-SA 3.0/4.0)

#character-encoding #java #decoding






相關問題

android webview顯示windows-1250字符集html的問題 (Trouble with android webview displaying windows-1250 charset html)

SQL Server 2008:字符編碼 (SQL Server 2008 : Character encoding)

刪除不可打印的字符 (Removing non-printable character)

電子郵件客戶端如何讀取內容類型標頭進行編碼? (How does an email client read the content-type headers for encoding?)

帶有 iText 7 的 PDF 中的希臘字符 (Greek characters in PDF with iText 7)

如何在 C 字符串中的文本或字母中添加下標字符? (How to add a subscript character to text or a letter in a C string?)

來自 URL 編碼問題的 NSArray (NSArray from URL encoding problem)

網絡上有免費提供的 HTML URL 編碼功能嗎?(在 C 中實現) (Is there any HTML URL encoding function freely available on web?? (Implementation in C))

讀取未知編碼的文本行 (Reading lines of text in unknown encoding)

Python - 以 Python 可以使用的格式編碼外來字符的方法? (Python - Way to encode foreign characters in format Python can work with?)

決定 HTTP 標頭的字符集。我應該簡單地把 utf-8 和 fuggedaboutit 放在一起嗎? (Deciding charset for HTTP Headers. Should i simply put utf-8 and fuggedaboutit?)

如何在 python 中將原始 unicode 轉換為 utf8-unicode? (How to convert raw unicode to utf8-unicode in python?)







留言討論