Java basics: Blocking IO

Source: Internet
Author: User

Java basics: Blocking IO
 

 

 

Note: Before reading this article, we recommend that you first read this blog to understand the basic concepts of blocking IO and non-blocking IO.

1. Stream 1. byte Stream

Input (InputStream)

Media Stream

FileInputStream

Read information from a file

PipedInputStream

Generate data used to write related PipedOutputStream, and implement the concept of "Pipeline"

ByteArrayInputStream

Memory buffer can be used as InputStream

Stream Processing

SequenceInputStream

Converts two or more inputstreams to a single InputStream.

ObjectInputStream

Object input stream

FilterInputStream subclass

 

BufferedInputStream

To prevent actual write operations during each read operation, it indicates "using a buffer zone"

DataInputStream

It can be used with DataOutputStream to read basic data types (int, char, long, etc.) from the stream in a portable manner)

LineNumberInputStream

 

PushbackInputStream

 

 

Output (OutputStream)

Media Stream

FileOutputStream

Used to write information to a file

PipedOutputStream

Any information written into it will be automatically used as the output of the relevant PipedInputStream, implementing the concept of "Pipeline"

ByteArrayOutputStream

Create a buffer in the memory. All data sent to the "stream" is placed in this buffer zone.

Stream Processing

ObjectOutputStream

Object output stream

FilterOutputStream subclass

 

BufferedOutputStream

Avoid the actual write operation when sending data every time, which indicates "using the Buffer Zone"

DataOutputStream

Used with DataInputStream to write basic data (int, char, long, etc.) to the stream in a portable manner)

PrintStream

It is used to produce formatted output. DataOutputStream stores the processed data and PrintStream processes the display.

 

2. Ghost stream

Input (Reader)

Media Stream

FileReader

FileInputStream

CharArrayReader

ByteArrayInputStream

PipedReader

PipedInputStream

Stream Processing

BufferedReader

BufferedInputStream

InputStreamReader

Used to convert InputStream to Reader

 

Output (Writer)

Media Stream

FileWriter

FileOuputStream

CharArrayWriter

ByteArrayOutputStream

PipedWriter

PipedOutputStream

Stream Processing

BufferedWriter

BufferedOutputStream

OutputStreamWriter

Used to convert OutputStream to Writer

 

Byte stream and byte stream:

(1) Different read/write units: byte streams are measured in 8 bits, and the byte streams are measured in characters. Based on the ing characters in the code table, multiple bytes may be read at a time.

(2) Different processing objects: byte streams can process all types of data (such as slice and avi), while the byte stream can only process character-type data.

(3) The byte stream itself does not use the buffer zone during operations, but directly operates the file itself. The swap stream will use the buffer zone after the operation, is to operate the stream through the buffer.

(4) The Inheritance level of Reader/Writer is designed to be internationalized. The byte stream only supports 8-bit read/write and cannot process 16-bit Unicode characters well, the char of java itself is 16 bits, and the addition of the escape stream is to support Unicode in all IO operations.

Suggestion: Try to use the byte stream whenever possible. If you cannot meet your requirements, consider byte stream !!!

 

Decorator ):

In the preceding stream, the "processing stream" of the byte stream and the bytes stream can encapsulate other "processing stream" and "media stream", while InputStreamReader and OutputStreamWriter can encapsulate the byte stream, provides the function of converting byte streams to bytes streams.

 

Ii. Input/output (IO) 1. file IO

Byte stream:

 

public static void main(String[] args)throws IOException {      String fileName=D:+File.separator+hello.txt;      File f=new File(fileName);      InputStream in=new FileInputStream(f);      byte[] b=new byte[1024];      int count =0;      int temp=0;      while((temp=in.read())!=(-1)){          b[count++]=(byte)temp;      }      in.close();      System.out.println(new String(b));    }

Ghost stream:

 

 

Public static void main (String [] args) throws IOException {String fileName = D: paifile.separator#hello.txt; File f = new File (fileName); char [] ch = new char [100]; reader read = new FileReader (f); int temp = 0; int count = 0; while (temp = read. read ())! = (-1) {ch [count ++] = (char) temp;} read. close (); System. out. println (content + new String (ch, 0, count ));}

 

2. Memory IO

 

public static void main(Stringargs[])throws IOException {         Stringstr = “Hello,jiyiqin”;ByteArrayInputStreambInput = new ByteArrayInputStream(str.getBytes());System.out.println(Convertingcharacters to Upper case  );for(int y = 0 ;y < 1; y++ ) {while(( c= bInput.read())!= -1) {System.out.println(Character.toUpperCase((char)c));}bInput.reset();}}

 

3. Pipeline I/O

 

Import java. io. inputStream; import java. io. outputStream; import java. io. pipedInputStream; import java. io. pipedOutputStream; public class PipedInputStreamTest {public static void main (String args []) {PipedInputStream input = new PipedInputStream (); PipedOutputStream output = new PipedOutputStream (); try {output. connect (input); new Thread (new OutputstreamRunnable (output )). start (); new Thread (new Inpu TstreamRunnable (input )). start ();} catch (Exception e) {e. printStackTrace () ;}}// output pipeline stream Thread class OutputstreamRunnable implementsRunnable {private OutputStream out; public OutputstreamRunnable (OutputStream output) {this. out = output ;}@ Override public void run () {String str = hello pipe; try {out. write (str. getBytes (); out. flush (); out. close ();} catch (Exception e) {e. printStackTrace ();}}} // Input pipeline stream Thread class InputstreamRunnable implementsRunnable {private InputStream in; public InputstreamRunnable (InputStream in) {this. in = in ;}@ Override public void run () {byte [] bs = new byte [1024]; int len =-1; try {if (len = in. read (bs ))! =-1) {System. out. println (newString (bs, 0, len) ;}} catch (Exception e) {e. printStackTrace ();}}}

 

4. Network I/O is commonly referred to as Java Socket programming, which is a blocking Java Network I/O.

Server code

 

public class Server {        public static void main(String args[]) throws IOException {       int port = 8888;       ServerSocket server = new ServerSocket(port);       Socket socket = server.accept();       Reader reader = new InputStreamReader(socket.getInputStream());        char chars[] = new char[64];        int len;        StringBuilder sb = new StringBuilder();        while ((len=reader.read(chars)) != -1) {           sb.append(new String(chars, 0, len));        }        System.out.println(from client:  + sb);        reader.close();        socket.close();        server.close();     }  }  

 

Client code

 

public class Client {        public static void main(String args[]) throws Exception {       String host = 127.0.0.1;      int port = 8888;      Socket client = new Socket(host, port);      Writer writer = new OutputStreamWriter(client.getOutputStream());        writer.write(Hello Server.);        writer.flush();      writer.close();        client.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.