Problem: When using Java program to read and write a TXT file containing Chinese, often read out or write content will appear garbled. The reason is actually very simple, that is, the coding of the system and the coding of the program adopt different coding format. In general, if you do not modify, Windows itself in the encoding format is GBK (and GBK and gb2312 is basically the same encoding), and the IDE encode do not modify, the default is Utf-8 encoding, which is why there will be garbled reasons. When manually created and written in the OS TXT file (GBK), with the program to read directly (Utf-8), will be garbled. In order to avoid possible Chinese garbled problems, it is best to specify the encoding format explicitly when the file is written and read out.
1, write the file:
public static void WriteFile (string filename, string filecontent)
{
try
{
File f = new File (fileName); C5/>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 ();
}
}
2, read the file:
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;
}