Java reading and writing TXT file to prevent the problem of Chinese garble code method
- 2020-04-01 04:34:41
- OfStack
Problem: when using Java programs to read and write TXT files containing Chinese, often there will be read or written content will appear gargoyles. The reason is actually very simple, is that the coding of the system and the coding of the program used a different coding format. In general, if you do not modify, Windows itself USES the encoding format is GBK (and GBK and gb2312 is basically the same encoding), and the IDE Encode is not modified, the default is utf-8 encoding, which is why there will be messy code. When the OS manually created and written to the TXT file (GBK), with the program to read directly (utf-8), will be garble. To avoid possible Chinese garble problems, it is best to explicitly specify the encoding format when the file is written and read.
1. Write documents:
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();
}
}
2. File reading:
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;
}