JAVA读取文件,避免中文乱码。
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;
}
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();
}
}
若写入的时候用
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
都会出现错误,不行。
p.s. 我刚开始用上述方法的时候还是出先乱码,后来发现是因为我的html文件的编码方式是不是utf-8,改成utf-8即可。
查看一个文件的编码方式,一个简单的办法是:用记事本打开它,然后另存为一个副本文件,在“另存为”的页面下方,“保存”按钮前面,如下图所示,会出现原文件的编码方式。
如果不是UTF-8,把它改成UTF-8,保存即可。
更多java知识请关注java基础教程栏目。