更新時間:2022-05-09 11:11:25 來源:動力節點 瀏覽6609次
動力節點小編來告訴大家java讀寫文件出現亂碼的解決方法。
1.讀文件:
/**
* 讀取文件內容
* @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("讀取文件內容操作出錯");
e.printStackTrace();
}
return fileContent;
}
InputStreamReader類是從字節流到字符流的橋接器:它使用指定的字符集讀取字節并將它們解碼為字符。 它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺的默認字符集。
2.寫文件
* @Title: writeFile
* @Description: 寫文件
* @param @param filePath 文件路徑
* @param @param fileContent 文件內容
* @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("寫文件內容操作出錯");
e.printStackTrace();
}
}
OutputStreamWriter是從字符流到字節流的橋接:使用指定的字符集將寫入其中的字符編碼為字節。它使用的字符集可以通過名稱指定,也可以明確指定,或者可以接受平臺的默認字符集。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習