您好,登錄后才能下訂單哦!
java讀寫file時如何避免亂碼?針對這個問題,這篇文章給出了相對應的分析和解答,希望能幫助更多想解決這個問題的朋友找到更加簡單易行的辦法。
1.讀文件:
/** * 讀取文件內(nèi)容 * * @param filePathAndName * String 如 c:\\1.txt 絕對路徑 * @return boolean */ public static String readFile(String filePath) { String fileContent = ""; try { File f = new File(filePath); if (f.isFile() && f.exists()) { InputStreamReader read = new InputStreamReader(new FileInputStream(f), "UTF-8"); BufferedReader reader = new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { fileContent += line; } read.close(); } } catch (Exception e) { System.out.println("讀取文件內(nèi)容操作出錯"); e.printStackTrace(); } return fileContent; }
InputStreamReader類是從字節(jié)流到字符流的橋接器:它使用指定的字符集讀取字節(jié)并將它們解碼為字符。 它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺的默認字符集。
2.寫文件
/** * * @Title: writeFile * @Description: 寫文件 * @param @param filePath 文件路徑 * @param @param fileContent 文件內(nèi)容 * @return void 返回類型 * @throws */ public static void writeFile(String filePath, String fileContent) { try { File f = new File(filePath); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); BufferedWriter writer = new BufferedWriter(write); writer.write(fileContent); writer.close(); } catch (Exception e) { System.out.println("寫文件內(nèi)容操作出錯"); e.printStackTrace(); } }
OutputStreamWriter是從字符流到字節(jié)流的橋接:使用指定的字符集將寫入其中的字符編碼為字節(jié)。它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺的默認字符集。
關(guān)于java讀寫file避免亂碼的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。