Java IO series 16 printstream (print output stream) detailed

Source: Internet
Author: User
Tags locale string format textout

This article extracts to: skywang12345

absrtact: introduces the meaning of each API of PrintStream, and analyzes the similarities and differences of PrintStream and DataOutputStream.

This chapter describes PrintStream and the difference between it and DataOutputStream. We first have a general understanding of PrintStream, and then in-depth study of its source code, and finally through the example to deepen its understanding.

PrintStream describes Rintstream as a printout stream that inherits from Filteroutputstream
PrintStream is used to decorate other output streams. It adds functionality to other output streams, enabling them to easily print various data-value representations.

Unlike other output streams, PrintStream never throws IOException; its resulting ioexception is captured by its own function and set to the wrong mark, and the user can return the error mark through CheckError (). To see if a ioexception is generated inside the printstream.
In addition, PrintStream provides automatic flush and character set setup capabilities. The so-called automatic flush, that is, the data written to PrintStream will immediately call the flush () function.

printstream Function List

* * Constructor///"Output flow out" as a printstream output stream, will not automatically flush, and the default character set//so-called "automatic flush", that is, every time the print (), println (), write () function, will call F
Lush () function;//and "Do not automatically flush", we need to manually invoke the flush () interface.
PrintStream (OutputStream out)//"output stream out" as the PrintStream output stream, automatically flush, and takes the default character set.
PrintStream (OutputStream out, Boolean AutoFlush)//will "output stream out" as the PrintStream output stream, automatically flush, using the CharsetName character set. PrintStream (OutputStream out, Boolean autoflush, String charsetname)//create file corresponding FileOutputStream,
The FileOutputStream is then used as the output stream of the PrintStream, not automatically flush, with the default character set. PrintStream (file file)//create the file corresponding FileOutputStream, and then the FileOutputStream as the PrintStream output stream, not automatically flush,
Adopt CharsetName Character Set. PrintStream (file file, String charsetname)//create filename corresponding to the FileOutputStream, and then the FileOutputStream as the output stream of the PrintStream,
Do not automatically flush, using the default character set. PrintStream (String fileName)//create fileName corresponding to the FileOutputStream, and then the FileOutputStream as the PrintStream output stream, not automatically flush,
Adopt CharsetName Character Set. PrintStream (String fileName, String charsetname)//append "character C" to the PrintStream output stream printstream append (char c)//will word Fu SheColumns are appended to the PrintStream output stream from start (including) to end (excluding) all characters "PrintStream append (charsequence charsequence, int start, int end)//Will"
All characters in the sequence of characters "append to the PrintStream output stream" PrintStream append (charsequence charsequence)//flush "PrintStream output stream buffer data" and check for errors
Boolean checkerror ()//Turn off "PrintStream output stream" synchronized void close ()//flush "PrintStream output stream buffer data". Tream format (Locale l, string format, Object ... args)//(based on "default Locale value (Area properties)" For formatting Data printstream format (string form At, Object ... args)//write "float data f corresponding string" to "PrintStream output stream", print actually calls the Write function void print (float f)//Will "double data d corresponds to the word String "writes to the PrintStream output stream", print actually calls the Write function void print (double D)//writes "string data str" to the "PrintStream output stream".     Print actually calls the Write function synchronized void print (string str)//writes the object o corresponding string to the PrintStream output stream, and print actually calls the Write function void Print (Object o)//write "character C string" to "PrintStream output stream", print actualWith the Write function void print (char c)//write "character array chars corresponding string" to "PrintStream output stream", print actually calls the Write function void print (char[) chars ///writes "Long data L string" to "PrintStream output stream", print actually calls the Write function void print (long L)//writes the "int data I string" to the PrintStream output stream ", print actually calls the Write function void print (int i)//Writes the string" Boolean data B "to the PrintStream output stream, and print actually calls the Write function void print (b Oolean b)//format "data args" according to "Locale Value (Area properties)" and write to "PrintStream output stream" PrintStream printf (Locale L, String format, O Bject args)//format "data args" according to the default locale value (zone properties) and write to the PrintStream output stream printstream printf (String format, OBJ ect.. args)//write "line break" to "PrintStream output stream", println actually calls the Write function void println ()//writes the string + newline character corresponding to float data to PrintStream     Output stream, println actually calls the Write function void println (float f)//Writes the "string + newline character for int data" to the PrintStream output stream, println actually calls the Write function void println (int i)///writes "string + newline character of Long data" to "PrintStream output stream", println actually calls the Write function void println (long L)//the string corresponding to object o + newline character "write to PrintStream output stream", PRIntln actually calls the Write function void println (Object o)//writes "character array chars corresponding string + newline character" to "PrintStream output stream", println actually calls the Write function void 
println (char[] chars)//writes "string str+ newline character" to "PrintStream output stream", println actually calls the Write function synchronized void println (String str) Writes the character C string + newline character to the PrintStream output stream, println actually calls the Write function void println (char c)//writes the string + newline character corresponding to the double data to the prints Tream output stream, println actually calls the Write function void println (double D)//writes the string + newline character corresponding to the Boolean data to the PrintStream output stream. Println actually calls the Write function void println (Boolean B)//writes the data onebyte to the PrintStream output stream. Onebyte is an int type, but actually writes only one byte synchronized void write (int onebyte)//writes "Length bytes from offset in buffer" to the PrintStream output stream
In void Write (byte[] buffer, int offset, int length)

Note:both print () and println () are written to the input stream after the arguments are converted to a string.
For example:

Equivalent to

Write (string.valueof (0x61));

The above statement writes the string "97" to the output stream. The 0x61 corresponds to a decimal number of 97.

Write (0x61)

The above statement writes the character ' a ' to the output stream. Because the 0x61 corresponds to the letter ' a ' of the ASCII code.


Looking at the following code, we can have a clearer understanding of these functions.
PrintStream Source Analysis (based on jdk1.7.40)

Package java.io;
Import Java.util.Formatter;
Import Java.util.Locale;
Import Java.nio.charset.Charset;
Import java.nio.charset.IllegalCharsetNameException;

Import java.nio.charset.UnsupportedCharsetException; public class PrintStream extends Filteroutputstream implements Appendable, closeable {//automatic flush//so-called "automatic flus
    H ", that is, every time you execute print (), println (), write () functions, all call the flush () function;//and" Do not automatically flush, "we need to manually invoke the flush () interface.

    Private Final Boolean AutoFlush; PrintStream whether the right produces an exception.

    When PrintStream has an exception, it is captured by itself and sets trouble to true private Boolean trouble = false;

    The object used for formatting private Formatter Formatter;
    BufferedWriter object that implements the "PrintStream support character set". Because PrintStream is a subclass of OutputStream, it does not natively support strings;//But BufferedWriter supports character sets,
    Therefore, the character set can be supported by creating a PrintStream corresponding BufferedWriter object through OutputStreamWriter.
    Private BufferedWriter TextOut;

    Private OutputStreamWriter charout; private static <T> t Requirenonnull (t obj, String message) {if (obj = = null) thRow new NullPointerException (message);
    return obj; 
        }//return CSN corresponding character set object private static Charset Tocharset (String CSN) throws Unsupportedencodingexception {
        Requirenonnull (CSN, "CharsetName");
        try {return charset.forname (CSN); catch (illegalcharsetnameexception| Unsupportedcharsetexception unused) {//unsupportedencodingexception should be thrown throw new U
        Nsupportedencodingexception (CSN);
    }///"Output out" as PrintStream output stream, AutoFlush flush mode, and takes the default character set.
        Private PrintStream (Boolean autoflush, outputstream out) {super (out);
        This.autoflush = AutoFlush;
        This.charout = new OutputStreamWriter (this);
    This.textout = new BufferedWriter (charout);
    ///"output stream out" as PrintStream output stream, automatically flush, using CharsetName character set.
        Private PrintStream (Boolean AutoFlush, OutputStream out, Charset Charset) {super (out);
       This.autoflush = AutoFlush; This.charout = new OutputStreamWriter (this, CharSet);
    This.textout = new BufferedWriter (charout); ///"output stream out" as PrintStream output stream, automatic flush, using CharsetName character Set Private PrintStream (Boolean autoflush, Charset Charset, O
    Utputstream out) throws Unsupportedencodingexception {This (AutoFlush, out, CharSet); ///"Output out" as an output stream of the PrintStream, will not automatically flush and takes the default character set public PrintStream (OutputStream out) {This (out, fals
    e);
        ///"Output flow out" as PrintStream output stream, automatically flush, and takes the default character set public PrintStream (OutputStream out, Boolean AutoFlush) {
    This is (AutoFlush, requirenonnull (out, "Null output stream"));
    ///"output stream out" as PrintStream output stream, automatically flush, using CharsetName character set. 
        Public PrintStream (OutputStream out, Boolean autoflush, String encoding) throws Unsupportedencodingexception {
    This is (AutoFlush, requirenonnull (out, "Null output stream"), Tocharset (encoding)); }//create filename corresponding to FileouTputstream, the FileOutputStream is then used as the PrintStream output stream, not automatically flush, with the default character set.
    Public PrintStream (String fileName) throws FileNotFoundException {This (false, new FileOutputStream (FileName)); //create filename corresponding to the FileOutputStream, and then the FileOutputStream as the PrintStream output stream, not automatically flush, using the CharsetName character set public prin Tstream (String fileName, String CSN) throws FileNotFoundException, Unsupportedencodingexception {//E
    Nsure CharSet is checked before the ' file is ' opened this (false, Tocharset (CSN), New FileOutputStream (FileName));
    //Create the file corresponding FileOutputStream, and then use the FileOutputStream as the PrintStream output stream, not automatically flush, with the default character set.
    Public printstream (file file) throws FileNotFoundException {This (false, new FileOutputStream (file));
    //Create the file corresponding FileOutputStream, and then use the FileOutputStream as the PrintStream output stream, not automatically flush, using the CSN character set.
        Public printstream (file file, String CSN) throws FileNotFoundException, Unsupportedencodingexception { Ensure CharSet is checked before the "file is opened" This (false, Tocharset (CSN), new FileOutputStream (file); private void Ensureopen () throws IOException {if (out = = null) throw new IOException ("Stream C
    Losed ");
    }//Flush "data in PrintStream output stream buffer".
            For example, PrintStream is decorated with fileoutputstream, then the call to flush writes the data to the file public void Flush () {synchronized () {
                try {ensureopen ();
            Out.flush ();
            catch (IOException x) {trouble = true; }} Private Boolean closing = false;
            * To avoid recursive closing//shutdown PrintStream public void close () {synchronized (this) {
                if (! closing) {closing = true;
                    try {textout.close ();
                Out.close ();
        catch (IOException x) {trouble = true;        } textout = null;
                Charout = null;
            out = null;
            }}//flush "PrintStream output stream buffer data" and check for errors public boolean checkerror () {if (out!= null)
        Flush ();
            if (out instanceof Java.io.PrintStream) {printstream PS = (printstream) out;
        return Ps.checkerror ();
    return trouble;
    } protected void SetError () {trouble = true;
    } protected void ClearError () {trouble = false; //Writes data B to the PrintStream output stream. b, although it is of type int, will actually write only one byte public void write (int b) {try {synchronized (this) {Ensur
                Eopen ();
                Out.write (b);
            if ((b = = ' \ n ') && AutoFlush) Out.flush ();
        } catch (Interruptedioexception x) {Thread.CurrentThread (). interrupt ();
     catch (IOException x) {       trouble = true;
    Write "Length bytes from off" in buf to the PrintStream output stream. public void Write (byte buf[], int out, int len) {try {synchronized (this) {Ensureop
                En ();
                Out.write (buf, off, Len);
            if (AutoFlush) Out.flush ();
        } catch (Interruptedioexception x) {Thread.CurrentThread (). interrupt ();
        catch (IOException x) {trouble = true;
    Write "All data in BUF" to the PrintStream output stream.
                private void Write (char buf[]) {try {synchronized (this) {Ensureopen ();
                Textout.write (BUF);
                Textout.flushbuffer ();
                Charout.flushbuffer ();
                            if (AutoFlush) {for (int i = 0; i < buf.length i++) if (buf[i] = = ' \ n ')
                Out.flush ();
  }          } catch (Interruptedioexception x) {Thread.CurrentThread (). interrupt ();
        catch (IOException x) {trouble = true;
    Write "string S" to the PrintStream output stream.
                private void Write (String s) {try {synchronized (this) {Ensureopen ();
                Textout.write (s);
                Textout.flushbuffer ();
                Charout.flushbuffer ();
            if (AutoFlush && (s.indexof (' \ n ') >= 0)) Out.flush ();
        } catch (Interruptedioexception x) {Thread.CurrentThread (). interrupt ();
        catch (IOException x) {trouble = true;
    ////write line break to PrintStream output stream.
                private void newline () {try {synchronized (this) {Ensureopen ();
                Textout.newline ();
                Textout.flushbuffer (); CharOut.flushbuffer ();
            if (AutoFlush) Out.flush ();
        } catch (Interruptedioexception x) {Thread.CurrentThread (). interrupt ();
        catch (IOException x) {trouble = true; Write the Boolean data string to the PrintStream output stream, and print actually calls the Write function public void print (Boolean b) {WR ITE (b?)
    "True": "false"); Write the character C string to the PrintStream output stream, and print actually calls the Write function public void print (char c) {write (string.valueof
    (c)); Write the "int data I string" into the PrintStream output stream, and print actually calls the Write function public void print (int i) {Write (string.value
    of (i)); Write the string "Long data L" to the PrintStream output stream, and print actually calls the Write function public void print (long l) {write (String.va
    Lueof (l)); ///Writes the string "float data F" to the PrintStream output stream, and print actually calls the Write function public void print (float f) {write (string.v
    Alueof (f)); ///write the string "double data D" toTo the PrintStream output stream, print actually calls the Write function public void print (double d) {write (string.valueof (d));
    //writes "character array S" to the PrintStream output stream, and print actually calls the Write function public void print (char s[]) {write (s); ///write "Object obj-corresponding string" to "PrintStream output stream", print actually calls the Write function public void print (object obj) {write (string.v
    Alueof (obj));
    ///write "line break" to "PrintStream output stream", println actually calls the Write function public void println () {newline (); ///write "string + newline character of Boolean data" to "PrintStream output stream", println actually calls the Write function public void println (Boolean x) {SYN
            Chronized (this) {print (x);
        NewLine (); Write the character x string + newline character to the PrintStream output stream, println actually calls the Write function public void println (char x) {SYNCHR
            Onized (this) {print (x);
        NewLine (); Write the string + newline character for int data to PrintStream output stream, println actually calls the Write function public void println (int x) {synch
   Ronized (This) {         print (x);
        NewLine (); Write the string + newline character for long data to the PrintStream output stream, println actually calls the Write function public void println (long x) {SYN
            Chronized (this) {print (x);
        NewLine (); Write the "string + newline character for float data" into the PrintStream output stream, println actually calls the Write function public void println (float x) {s
            Ynchronized (this) {print (x);
        NewLine ();
        Write the string + newline character for double data into the PrintStream output stream, println actually calls the Write function public void println (double x) {
            Synchronized (this) {print (x);
        NewLine (); Write "character array x+ newline" to "PrintStream output stream", println actually calls the Write function public void println (char x[]) {Synchron
            Ized (this) {print (x);
        NewLine (); Write the string x+ newline character to the PrintStream output stream, println actually calls the Write function public void println (string x) {Synchroni
            Zed (This) {print (x); NewlINE (); Write the string + newline character of object o to the PrintStream output stream, println actually calls the Write function public void println (object x) {Stri
        ng s = string.valueof (x);
            Synchronized (this) {print (s);
        NewLine ();  "Data args" is formatted according to the "Default locale value (Zone properties)" format and written to the PrintStream output stream in public printstream printf (String format,
    Object ... args) {return format (format, args); ///"Data args" is based on the locale value (region
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.