Java讀取、寫(xiě)入文件如何解決亂碼問(wèn)題
讀取文件流時(shí),經(jīng)常會(huì)遇到亂碼的現(xiàn)象,造成亂碼的原因當(dāng)然不可能是一個(gè),這里主要介紹因?yàn)槲募幋a格式而導(dǎo)致的亂碼的問(wèn)題。首先,明確一點(diǎn),文本文件與二進(jìn)制文件的概念與差異。
文本文件是基于字符編碼的文件,常見(jiàn)的編碼有ASCII編碼,UNICODE編碼、ANSI編碼等等。二進(jìn)制文件是基于值編碼的文件,你可以根據(jù)具體應(yīng)用,指定某個(gè)值是什么意思(這樣一個(gè)過(guò)程,可以看作是自定義編碼。)
因此可以看出文本文件基本上是定長(zhǎng)編碼的(也有非定長(zhǎng)的編碼如UTF-8)。而二進(jìn)制文件可看成是變長(zhǎng)編碼的,因?yàn)槭侵稻幋a嘛,多少個(gè)比特代表一個(gè)值,完全由你決定。
對(duì)于二進(jìn)制文件,是千萬(wàn)不能使用字符串的,因?yàn)樽址J(rèn)初始化時(shí)會(huì)使用系統(tǒng)默認(rèn)編碼,然而,二進(jìn)制文件因?yàn)樽远x編碼自然與固定格式的編碼會(huì)有所沖突,所以對(duì)于二進(jìn)制的文件只能采用字節(jié)流讀取、操作、寫(xiě)入。
對(duì)于文本文件,因?yàn)榫幋a固定,所以只要在讀取文件之前,采用文件自身的編碼格式解析文件,然后獲取字節(jié),再然后,通過(guò)指定格式初始化字符串,那么得到的文本是不會(huì)亂碼的。雖然,二進(jìn)制文件也可以獲取到它的文本編碼格式,但是那是不準(zhǔn)確的,所以不能同日而語(yǔ)。
具體操作如下:
1)獲取文本文件的格式
public static String getFileEncode(String path) { String charset ="asci"; byte[] first3Bytes = new byte[3]; BufferedInputStream bis = null; try { boolean checked = false; bis = new BufferedInputStream(new FileInputStream(path)); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1) return charset; if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) { charset = "Unicode";//UTF-16LE checked = true; } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) { charset = "Unicode";//UTF-16BE checked = true; } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) { charset = "UTF8"; checked = true; } bis.reset(); if (!checked) { int len = 0; int loc = 0; while ((read = bis.read()) != -1) { loc++; if (read >= 0xF0) break; if (0x80 <= read && read <= 0xBF) //單獨(dú)出現(xiàn)BF以下的,也算是GBK break; if (0xC0 <= read && read <= 0xDF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) //雙字節(jié) (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB編碼內(nèi) continue; else break; } else if (0xE0 <= read && read <= 0xEF) { //也有可能出錯(cuò),但是幾率較小 read = bis.read(); if (0x80 <= read && read <= 0xBF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else break; } else break; } } //TextLogger.getLogger().info(loc + " " + Integer.toHexString(read)); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } return charset; } private static String getEncode(int flag1, int flag2, int flag3) { String encode=""; // txt文件的開(kāi)頭會(huì)多出幾個(gè)字節(jié),分別是FF、FE(Unicode), // FE、FF(Unicode big endian),EF、BB、BF(UTF-8) if (flag1 == 255 && flag2 == 254) { encode="Unicode"; } else if (flag1 == 254 && flag2 == 255) { encode="UTF-16"; } else if (flag1 == 239 && flag2 == 187 && flag3 == 191) { encode="UTF8"; } else { encode="asci";// ASCII碼 } return encode; }
2)通過(guò)文件的編碼格式讀取文件流
/** * 通過(guò)路徑獲取文件的內(nèi)容,這個(gè)方法因?yàn)橛玫搅俗址鳛檩d體,為了正確讀取文件(不亂碼),只能讀取文本文件,安全方法! */ public static String readFile(String path){ String data = null; // 判斷文件是否存在 File file = new File(path); if(!file.exists()){ return data; } // 獲取文件編碼格式 String code = FileEncode.getFileEncode(path); InputStreamReader isr = null; try{ // 根據(jù)編碼格式解析文件 if("asci".equals(code)){ // 這里采用GBK編碼,而不用環(huán)境編碼格式,因?yàn)榄h(huán)境默認(rèn)編碼不等于操作系統(tǒng)編碼 // code = System.getProperty("file.encoding"); code = "GBK"; } isr = new InputStreamReader(new FileInputStream(file),code); // 讀取文件內(nèi)容 int length = -1 ; char[] buffer = new char[1024]; StringBuffer sb = new StringBuffer(); while((length = isr.read(buffer, 0, 1024) ) != -1){ sb.append(buffer,0,length); } data = new String(sb); }catch(Exception e){ e.printStackTrace(); log.info("getFile IO Exception:"+e.getMessage()); }finally{ try { if(isr != null){ isr.close(); } } catch (IOException e) { e.printStackTrace(); log.info("getFile IO Exception:"+e.getMessage()); } } return data; }
3)通過(guò)文件指定的格式寫(xiě)入文件
/** * 按照指定的路徑和編碼格式保存文件內(nèi)容,這個(gè)方法因?yàn)橛玫搅俗址鳛檩d體,為了正確寫(xiě)入文件(不亂碼),只能寫(xiě)入文本內(nèi)容,安全方法 * * @param data * 將要寫(xiě)入到文件中的字節(jié)數(shù)據(jù) * @param path * 文件路徑,包含文件名 * @return boolean * 當(dāng)寫(xiě)入完畢時(shí)返回true; */ public static boolean writeFile(byte data[], String path , String code){ boolean flag = true; OutputStreamWriter osw = null; try{ File file = new File(path); if(!file.exists()){ file = new File(file.getParent()); if(!file.exists()){ file.mkdirs(); } } if("asci".equals(code)){ code = "GBK"; } osw = new OutputStreamWriter(new FileOutputStream(path),code); osw.write(new String(data,code)); osw.flush(); }catch(Exception e){ e.printStackTrace(); log.info("toFile IO Exception:"+e.getMessage()); flag = false; }finally{ try{ if(osw != null){ osw.close(); } }catch(IOException e){ e.printStackTrace(); log.info("toFile IO Exception:"+e.getMessage()); flag = false; } } return flag; }
4)對(duì)于二進(jìn)制文件而且內(nèi)容很少的,例如Word文檔等,可以使用如下方式讀取、寫(xiě)入文件
/** * 從指定路徑讀取文件到字節(jié)數(shù)組中,對(duì)于一些非文本格式的內(nèi)容可以選用這個(gè)方法 * 457364578634785634534 * @param path * 文件路徑,包含文件名 * @return byte[] * 文件字節(jié)數(shù)組 * */ public static byte[] getFile(String path) throws IOException { FileInputStream stream=new FileInputStream(path); int size=stream.available(); byte data[]=new byte[size]; stream.read(data); stream.close(); stream=null; return data; } /** * 把字節(jié)內(nèi)容寫(xiě)入到對(duì)應(yīng)的文件,對(duì)于一些非文本的文件可以采用這個(gè)方法。 * @param data * 將要寫(xiě)入到文件中的字節(jié)數(shù)據(jù) * @param path * 文件路徑,包含文件名 * @return boolean isOK 當(dāng)寫(xiě)入完畢時(shí)返回true; * @throws Exception */ public static boolean toFile(byte data[], String path) throws Exception { FileOutputStream out=new FileOutputStream(path); out.write(data); out.flush(); out.close(); out=null; return true; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
Spring定時(shí)任務(wù)關(guān)于@EnableScheduling的用法解析
這篇文章主要介紹了Spring定時(shí)任務(wù)關(guān)于@EnableScheduling的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06java實(shí)現(xiàn)遠(yuǎn)程桌面的實(shí)例代碼
下面小編就為大家分享一篇java實(shí)現(xiàn)遠(yuǎn)程桌面的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01JavaWeb ServletContext基礎(chǔ)與應(yīng)用詳細(xì)講解
ServletConfig對(duì)象,叫Servlet配置對(duì)象。主要用于加載配置文件的初始化參數(shù)。我們知道一個(gè)Web應(yīng)用里面可以有多個(gè)servlet,如果現(xiàn)在有一份數(shù)據(jù)需要傳給所有的servlet使用,那么我們就可以使用ServletContext對(duì)象了2023-01-01SpringBoot一個(gè)接口多個(gè)實(shí)現(xiàn)類的調(diào)用方式總結(jié)
這篇文章主要介紹了SpringBoot一個(gè)接口多個(gè)實(shí)現(xiàn)類的調(diào)用方式,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01完美解決Spring Boot前端的Access-Control-Allow-Origin跨域問(wèn)題
這篇文章主要介紹了完美解決Spring Boot前端的Access-Control-Allow-Origin跨域問(wèn)題,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05詳解OAuth2 Token 一定要放在請(qǐng)求頭中嗎
這篇文章主要介紹了詳解OAuth2 Token 一定要放在請(qǐng)求頭中嗎,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Spring Boot和Kotlin的無(wú)縫整合與完美交融
這篇文章主要給大家介紹了關(guān)于Spring Boot和Kotlin的無(wú)縫整合與完美交融的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06MyBatis-plus使用lambda條件構(gòu)造器報(bào)錯(cuò)問(wèn)題及解決
這篇文章主要介紹了MyBatis-plus使用lambda條件構(gòu)造器報(bào)錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01maven項(xiàng)目install時(shí)忽略執(zhí)行test方法的總結(jié)
這篇文章主要介紹了maven項(xiàng)目install時(shí)忽略執(zhí)行test方法的總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03在java8中使用流區(qū)分質(zhì)數(shù)與非質(zhì)數(shù)詳解
這篇文章主要介紹了在java8中使用流區(qū)分質(zhì)數(shù)與非質(zhì)數(shù)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12