java读写文件避免中文乱码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1、JAVA读取文件,避免中文乱码。
/**
* 读取文件内容
*
* @param filePathAndName
* String 如c:\\1.txt 绝对路径
* @return boolean
*/
public static String readFile(String filePathAndName) {
String fileContent = "";
try {
File f = new File(filePathAndName);
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;
}
2、JAVA写入文件,避免中文乱码。
public static void writeFile(String filePathAndName, String fileContent) {
try {
File f = new File(filePathAndName);
if (!f.exists()) {
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
BufferedWriter writer=new BufferedWriter(write);
//PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
//PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
writer.write(fileContent);
writer.close();
} catch (Exception e) {
System.out.println("写文件内容操作出错");
e.printStackTrace();
}
}
我试过写入的时候用
1、PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
2、PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
都不行。
以上代码经过运行可以避免中文乱码,关键是要编码转换。