Java读写txt文件中文乱码有关问题
Java读写txt文件中文乱码问题
问题:在用Java程序进行读写含中文的txt文件时,经常会出现读出或写入的内容会出现乱码。原因其实很简单,就是系统的编码和程序的编码采用了不同的编码格式。通常,假如自己不修改的话,windows自身采用的编码格式是gbk(而gbk和gb2312基本上是一样的编码方式),而IDE中Encode不修改的话,默认是utf-8的编码,这就是为什么会出现乱码的原因。当在OS下手工创建并写入的txt文件(gbk),用程序直接去读(utf-8),就会乱码。为了避免可能的中文乱码问题,最好在文件写入和读出的时候显式指定编码格式。
1、写文件:
public static void writeFile(String fileName, String fileContent)
{
try
{
File f = new File(fileName);
if (!f.exists())
{
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"gbk");
BufferedWriter writer=new BufferedWriter(write);
writer.write(fileContent);
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void writeFile(String fileName, String fileContent)
{
try
2、读文件:
public static String readFile(String fileName)
{
String fileContent = "";
try
{
File f = new File(fileName);
if(f.isFile()&&f.exists())
{
InputStreamReader read = new InputStreamReader(new FileInputStream(f),"gbk");
BufferedReader reader=new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null)
{
fileContent += line;
}
read.close();
}
} catch (Exception e)
{
e.printStackTrace();
}
return fileContent;
}
public static String readFile(String fileName)
{
String fileContent = "";
try
{
File f = new File(fileName);
if(f.isFile()&&f.exists())
{
InputStreamReader read = new InputStreamReader(new FileInputStream(f),"gbk");
BufferedReader reader=new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null)
{
fileContent += line;
}
read.close();
}
} catch (Exception e)
{
e.printStackTrace();
}
return fileContent;
}