Previously introduced PrintStream, it can be Java's basic data types, such as data, directly into the system default encoding the corresponding characters, and then output to the OutputStream. The java.io.PrintWriter described here is functionally similar to PrintStream, which, in addition to accepting outputstream instances as variables, PrintWriter can accept writer objects as output objects. It is convenient to use PrintWriter when you used to use the writer object for character processing and now want to apply the println () method.
The following example shows the PrintStream and PrintWriter two objects in the process of processing the same output purposes, the program will output the Simplified Chinese GB2312 encoded text to the specified file.
Import java.io.*;
Import java.util.*;
public class Streamwriterdemo {public static void main (string[] args) {try {//"Simplified Chinese" four-word GB2312 encoding byte[] sim = {(byte) 0xbc, (Byte) 0xf2, (Byte) 0xcc, (Byte) 0xe5, (by
TE) 0xd6, (Byte) 0xd0, (Byte) 0xce, (byte) 0xc4};
Array as stream source Bytearrayinputstream Bytearrayinputstream = new Bytearrayinputstream (SIM);
InputStreamReader InputStreamReader = new InputStreamReader (Bytearrayinputstream, "GB2312");
PrintWriter can accept writer instances as variable printwriter printwriter = new PrintWriter (New OutputStreamWriter (
New FileOutputStream (Args[0]), "GB2312"));
int in = 0;
Printwriter.print ("PrintWriter:");
Writes the array content while (in = Inputstreamreader.read ())!=-1) {printwriter.print ((char) in);
} printwriter.println ();
Printwriter.close ();
Bytearrayinputstream.reset (); PrintStream Accept OUtputstream instance as variable printstream printstream = new PrintStream (new FileOutputStream (Args[0],true), True, "GB2312");
Printstream.print ("PrintStream:");
Write array content while (in = Inputstreamreader.read ())!=-1} {printstream.print ((char) in);
System.out.println (Integer.tohexstring (in));
} printstream.println ();
Inputstreamreader.close ();
Printstream.close ();
catch (ArrayIndexOutOfBoundsException e) {System.out.println ("no file Specified");
catch (IOException e) {e.printstacktrace (); }
}
}Run the following command the Java Streamwriterdemo Output.txt screen will output:
7b80
4f53
4e2d
6587
Unicode encoding value for "Simplified Chinese".