歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java utf-8文件處理bom頭

Java utf-8文件處理bom頭

日期:2017/3/1 9:17:24   编辑:Linux編程

UTF?

UTF,是UnicodeTransformationFormat的縮寫,意為Unicode轉換格式。 即怎樣將Unicode定義的數字轉換成程序數據。utf是對Unicode的一種編碼格式化。 JVM裡面的任何字符串資源都是Unicode,就是說,任何String類型的數據都是Unicode編碼。沒有例外。既然只有一種編碼,那麼,我們可以這麼說,JVM裡面的String是不帶編碼的。String相當於 char[]。

JVM裡面的 byte[] 數據是帶編碼的。比如,Big5,GBK,GB2312,UTF-8之類的(GBK並不屬於utf)。

一個GBK編碼的byte[] 轉換成 String,其實就是從GBK編碼向Unicode編碼轉換。

一個String轉換成一個Big5編碼的byte[],其實就是從Unicode編碼向Big5編碼轉換。 我們在解析的時候就要注意是不是utf編碼。

有幾種UTF?

這裡用char、char16_t、char32_t分別表示無符號8位整數,無符號16位整數和無符號32位整數。UTF-8、UTF-16、UTF-32分別以char、char16_t、char32_t作為編碼單位。

什麼是bom?

放在文件頭用於標示Unicode編碼格式。

bom會引起什麼問題?

記事本保存的文件會存儲bom,在解析的時候,在頭部會多出一個亂碼。

如何解決:

編程時根據具體的編碼類型剔除頭bom

public static String ReadFile(String path,StringFilter filter) throws IOException {

File file = new File( path);

if (! file.exists()) {

throw new IOException( "文件不存在" );

}

BufferedReader reader = null;

StringBuffer laststr = new StringBuffer();

InputStream in= new FileInputStream( file);

try {

reader = new BufferedReader( new UnicodeReader(in,"utf-8" ));

String tempString = null;

while (( tempString = reader.readLine()) != null) {

if ( filter!= null) {

tempString= filter.RemoveString( tempString);

}

laststr.append( tempString);

}

reader.close();

} catch (IOException e) {

throw new IOException( "文件讀寫錯誤" );

} finally {

if ( reader != null) {

try {

reader.close();

} catch (IOException e1) {

throw new IOException( "文件流關閉錯誤" );

}

}

}

return laststr.toString();

}

Copyright © Linux教程網 All Rights Reserved