Use a PrintWriter to write two Chinese characters and read them back in Java

Description

The following code shows how to use a PrintWriter to write two Chinese characters and read them back.

An InputStreamReader reads bytes and translates them into characters using the specified character set.

InputStreamReader is ideal for reading from the output of an OutputStreamWriter or a PrintWriter.

Example


//  ww w  .  j ava2s  .co  m

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
  public static void main(String[] args) {
    try {
      char[] chars = new char[2];
      chars[0] = '\u4F60';
      chars[1] = '\u597D';
      String encoding = "GB18030";
      File textFile = new File("C:\\temp\\myFile.txt");
      PrintWriter writer = new PrintWriter(textFile,encoding);
      writer.write(chars);
      writer.close();

      // read back
      InputStreamReader reader = new InputStreamReader(new FileInputStream(textFile), encoding);
      char[] chars2 = new char[2];
      reader.read(chars2);
      System.out.print(chars2[0]);
      System.out.print(chars2[1]);
      reader.close();
    } catch (IOException e) {
      System.out.println(e.toString());
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip