Java solves the problem of reading and writing Chinese characters in local files

  • 2020-06-03 06:22:01
  • OfStack

Java solves the problem of reading and writing Chinese characters in local files

Preface:

When Java program is used to read and write txt files in Chinese, it often occurs that the contents read or written will be confused. The reason is actually very simple, is that the coding of the system and the coding of the program adopt different coding format. In general, if windows does not modify itself, the encoding format adopted by windows itself is gbk(whereas gbk and gb2312 are basically the same encoding style), while Encode in IDE does not modify, the default encoding is utf-8, which is the reason for the confusion. When an txt file (gbk) is created and written manually under OS, it is read programmatically (utf-8) and the code is scrambled. To avoid possible Chinese scrambling problems, it is best to explicitly specify the encoding format when the file is written and read.

Read local file by line:


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+"\n";
        }
        read.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return fileContent;
  }

Write to local file:


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();
    }
  }

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: