更新時(shí)間:2022-05-09 11:11:25 來源:動(dòng)力節(jié)點(diǎn) 瀏覽7002次
動(dòng)力節(jié)點(diǎn)小編來告訴大家java讀寫文件出現(xiàn)亂碼的解決方法。
1.讀文件:
/**
* 讀取文件內(nèi)容
* @param filePathAndName
* String 如 c:\\1.txt 絕對(duì)路徑
* @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)容操作出錯(cuò)");
e.printStackTrace();
}
return fileContent;
}
InputStreamReader類是從字節(jié)流到字符流的橋接器:它使用指定的字符集讀取字節(jié)并將它們解碼為字符。 它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺(tái)的默認(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)容操作出錯(cuò)");
e.printStackTrace();
}
}
OutputStreamWriter是從字符流到字節(jié)流的橋接:使用指定的字符集將寫入其中的字符編碼為字節(jié)。它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺(tái)的默認(rèn)字符集。
相關(guān)閱讀
Java實(shí)驗(yàn)班
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
Java就業(yè)班
有基礎(chǔ) 直達(dá)就業(yè)
Java夜校直播班
業(yè)余時(shí)間 高薪轉(zhuǎn)行
Java在職加薪班
工作1~3年,加薪神器
Java架構(gòu)師班
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)