java讀寫文件避免亂碼的方法:
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é)并將它們解碼為字符。 它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺的默認(rèn)字符集。
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é)。它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺的默認(rèn)字符集。