簡體   English   中英

將字符串從UTF-8轉換為ISO-8859-1

[英]Translate a string from UTF-8 to ISO-8859-1

我正在從數據庫中讀取UTF-8字符集的一些文本數據。 但是我需要生成一個帶有ISO-8859-1字符集的文件。

為此,我使用以下代碼。

StringBuilder filaStr = new StringBuilder();
filaStr.append("INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN");//this is a UTF-8 string got from my database
Charset utf8 = Charset.forName("UTF-8");
Charset iso8859_1 = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = utf8.newDecoder();
CharsetEncoder encoder = iso8859_1.newEncoder();
CharBuffer decodedCB = decoder.decode(ByteBuffer.wrap(filaStr.toString().getBytes()));
ByteBuffer encodedBB = encoder.encode(decodedCB);
pw.write(new String(encodedBB.array()));//pw is the PrintWriter that writes in the file
pw.write(new String(encodedBB.array(), iso8859_1));

當我使用UTF-8字符集通過文本編輯器打開文件時,看到以下內容:

INGENIER�A DE EJECUCI�N EN ADMINISTRACI�N
INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN

當我使用ISO-8859-1打開它時,會看到以下內容:

INGENIER�A DE EJECUCI�N EN ADMINISTRACI�N
INGENIERÃA DE EJECUCIÃN EN ADMINISTRACIÃN

理想的結果是以ISO-8859-1字符集打印INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN

問題是PrintWriter,必須使用所需的字符集對其進行初始化。

PrintWriter pw = new PrintWriter(file, "ISO-8859-1"); 解決了問題,甚至不需要CharsetDecoderCharsetEncoder

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM