[Java I/O] character output stream Writer briefly summarizes the output stream writer

Source: Internet
Author: User

[Java I/O] character output stream Writer briefly summarizes the output stream writer

The Reader and Writer are similar to the previous character input stream Reader;

Character output stream Writer

This article will briefly summarize the character output stream Writer in the java I/O Stream:

In general, each character output stream class has a corresponding purpose, as follows:

    • Character output stream base class: Writer
    • Byte Transfer bytes stream: OutputStreamWriter // write characters to the byte output stream
    • Character file writing: FileWriter // write characters to the file
    • Character array to character stream: CharArrayWriter // write characters to the character array
    • Internal Thread communication (pipeline): PipedWriter // write characters to the pipeline
    • String to reverse stream: StringWriter // write characters to StringBuffer to construct a string
    • Buffer stream: BufferedWriter // You can describe other character output streams to increase the buffer function.
    • Filter stream: FilterWriter // You can describe other character output streams and add the filter function.
    • Formatting and writing characters: PrintWriter: // You can describe other character output streams and add functions such as formatting and writing data.

Let's look at the Writer's composition structure (including the character input stream Reader );

The following describes the output streams of each character in detail;

OutputStreamWriter

OutputStreamWriter inherits the bytes stream abstract class Writer. Each constructor contains a byte stream OutputStream input parameter.Write characters to the byte output stream;

PS: whether it is the processing of byte streams in the constructor (StreamDecoder. forOutputStreamWriter), or StreamDecoder. write). The underlying layer is implemented through the StreamDecoder class. If you are interested, you can learn more ~

For example, do not handle exceptions for ease of reading:

Package com. pickers. io; import java. io. IOException; import java. io. outputStreamWriter; import java. io. writer; public class IOTest {public static void main (String [] args) throws IOException {// get a character output stream through the "standard" Byte output stream Writer writer = new OutputStreamWriter (System. out); // write the character writer to the internal stream. write ("hello ~ "); // Close stream writer. close ();}}
FileWriter

FileWriter inherits the bytes stream OutputStreamWriter,ToWrite characters to local filesTo view its constructor method, a FileOutputStream byte stream object is first generated based on the input parameters, and then the parent class OutputStreamWriter's constructor is called to obtain the complete stream;

A simple example:

Package com. pickers. io; import java. io. fileWriter; import java. io. IOException; import java. io. writer; public class IOTest {public static void main (String [] args) throws IOException {// get the character output stream Writer writer Writer = new FileWriter ("C: \ test.txt "); // write the character writer. write ('A'); // refresh the buffer writer of the stream. flush (); // close the stream writer. close ();}}
CharArrayWriter

CharArrayReader allows usToWrite characters in character arrayIn the constructor, you can specify the size of the character array, and the character array will be automatically increased in the subsequent write process;

A simple example:

Package com. pickers. io; import java. io. charArrayWriter; import java. io. IOException; public class IOTest {public static void main (String [] args) throws IOException {// create a sequence stream and specify the initial buffer size CharArrayWriter writer = new CharArrayWriter (6 ); // write the character writer. write ("aaabbb"); // obtain the character array System from the character output stream. out. println (writer. toCharArray (); // closes the stream writer. close ();}}
PipedWriter

You can use PipedWriter and PipedReader to create pipeline Stream pipelines. Threads can communicate with each other through pipelines. Note: two threads in the same JVM must be used;

PipedWriter is generally used with PipedReader. One thread writes data to the pipeline through PipedWriter, And the other thread reads data from the pipeline through PipedReader. Note that reading and writing will block the thread, as shown in the following example:

Package com. pickers. io; import java. io. IOException; import java. io. pipedReader; import java. io. pipedWriter; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class IOTest {public static void main (String [] args) throws IOException {final PipedWriter pw = new PipedWriter (); final PipedReader pr = new PipedReader (pw ); executorService es = Executors. newFixedThreadPoo L (2); es.exe cute (new Runnable () {@ Override public void run () {try {pw. write ("hello ~ ");} Catch (IOException e) {e. printStackTrace () ;}}); es.exe cute (new Runnable () {@ Override public void run () {char [] cbuffer = new char [6]; try {// will cause thread blocking pr. read (cbuffer, 0, 6);} catch (IOException e) {e. printStackTrace ();} System. out. println (cbuffer );}});}}
BufferedWriter

This character stream can be used to describe other character output streams. It can provide a character output buffer for other character output streams, which can be written at one time to avoid writing data into the external media by one byte each time, here we use the decorator mode in the design mode. For details, refer to the one I wrote earlier,

Http://www.cnblogs.com/chenpi/p/5173818.html

The decorated ghost stream can have more behaviors, such as the newLine method;

For example, read an external file:

Package com. pickers. io; import java. io. bufferedWriter; import java. io. fileWriter; import java. io. IOException; public class IOTest {public static void main (String [] args) throws IOException {// create a buffer character output stream, set the buffer size to 10 k BufferedWriter writer = new BufferedWriter (new FileWriter ("C: \ test.txt"), 10*1024); // write the character writer to the buffer. write ("aaa"); writer. newLine (); writer. write ("bbb"); // close the stream writer. close ();}}
FilterWriter

The abstract class FilterWriter is the base class for implementing custom filtering and output of the response stream. from the implementation of the source code, it simply overwrites all the methods in the Writer and feels useless, because there is already an abstract class Writer;

StringWriter

Character output stream, which can be a string, which is implemented through StringBuffer internally,

A simple example

package com.pichen.io;import java.io.IOException;import java.io.StringWriter;public class IOTest {    public static void main(String[] args) throws IOException {        StringWriter writer = new StringWriter();        writer.write("hello ");        writer.write("world~");        System.out.println(writer.toString());    }}
PrintWriter

Allows you to write formatted data to the character output stream. For example, you can write formatted data to the console;

package com.pichen.io;import java.io.IOException;import java.io.PrintWriter;public class IOTest {    public static void main(String[] args) throws IOException {        PrintWriter writer = new PrintWriter(System.out);        writer.write("hello ");        writer.write("world~");                writer.printf("%5d", 101);                writer.close();    }}

 

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.