最近在做HTML静态生成,需要从硬盘上把模版文件的内容读出来。然后,替换相关标签写到指定的文件中。无论是读写,都遇到了中文乱码问题。试过多种方法,发现下面一种可以避免中文乱码。(无论读取还是写入一定要进行编码转换。)
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));
都不行。
以上代码经过运行可以避免中文乱码,关键是要编码转换。
追答亲,参考,有任何疑问请联系我
记得采纳
本回答被提问者和网友采纳