java用字節(jié)數組解決FileInputStream讀取漢字出現亂碼問題
更新時間:2024年05月30日 14:51:33 作者:深入技術了解原理
這篇文章主要介紹了java用字節(jié)數組解決FileInputStream讀取漢字出現亂碼問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
用字節(jié)數組解決FileInputStream讀取漢字出現亂碼
package hanjia; import java.io.*; //用“字節(jié)數組”方式讀取文本文件內容,然后利用String(byte[] bytes) //或String(byte[] bytes, int offset, int length) 構造新字符串來輸出。 //解決思路:先用較大的字節(jié)數組讀取文本文件內容,將調用String類構造方法將字節(jié)數組內容組合成有意義的漢字 class hanjia { public static void main(String args[]) throws IOException { FileInputStream infile = new FileInputStream("D:/KuGou/f.txt"); try { byte[] b = new byte[128];// 定義一個字節(jié)數組 int i = infile.read(b);// 讀取數據存放到字節(jié)數組中,read()返回值-1表示結束 while (i != -1) {// 讀指針到達輸出流尾部時結束 System.out.print(new String(b, 0, i));//從開頭到結束將字節(jié)數組內容轉換為字符串,并輸出 i = infile.read(b);// 讀取后續(xù)數據存放到字節(jié)數組中 } } catch (IOException e) { System.out.println(e.getMessage()); } finally { infile.close();// 關閉輸入流 } } }
解決FileInputStream讀取ANSI格式txt中文亂碼
GBK中文轉為byte后以負數開頭,正常來說為連續(xù)兩個負數,生僻字可能為一個負數和一個整數,所以需要特殊處理一下
注:utf-8的txt一個中文占三個byte數組,故此方法不適用
import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; public class FileInputStreamTest03 { public static void main(String[] args) { // test String s = "中c國Dh丄"; byte[] bs = new byte[10]; try { bs = s.getBytes("GBK"); System.out.println(Arrays.toString(bs)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String s2 = null; try { s2 = new String(bs, "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(s2); // main FileInputStream fp = null; try { fp = new FileInputStream("C:\\Users\\dell\\Documents\\a代碼備份\\python\\爬蟲\\bilibili\\list.txt"); byte[] b = new byte[10]; int num; while ((num = fp.read(b)) != -1){ int pos = 0; // 記錄負值個數,中文GBK為兩個負值 for (byte b1 : b) { if (b1 < 0){ pos++; } } // System.out.println(Arrays.toString(b)); if (pos%2 != 0 && b[b.length-1] < 0){ int nextValue=fp.read(); int size = b.length; int nextLen=size+1; //字節(jié)數組擴容一位 b = Arrays.copyOf(b,nextLen); b[size]= (byte) nextValue; String content=new String(b, 0, nextLen, "GBK"); System.out.print(content); } else { System.out.print(new String(b, 0, num, "GBK")); } } } catch (IOException e) { e.printStackTrace(); } finally { if (fp != null){ try { fp.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java后端返回數據給前端時去除值為空或NULL的屬性、忽略某些屬性代碼示例
在Java開發(fā)中我們處理JSON數據時經常會遇到空值(null)的情況,這篇文章主要給大家介紹了關于java后端返回數據給前端時去除值為空或NULL的屬性、忽略某些屬性的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-07-07解決nacos升級spring cloud 2020.0無法使用bootstrap.yml的問題
這篇文章主要介紹了解決nacos升級spring cloud 2020.0無法使用bootstrap.yml的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Springboot下使用Redis管道(pipeline)進行批量操作
本文主要介紹了Spring?boot?下使用Redis管道(pipeline)進行批量操作,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05