Java IO theory notes

Source: Internet
Author: User

1. Java IO stream

Io is the basis for implementing Input and Output in java. It can easily complete the input and output operations of data. Java abstracts different input and output into a stream, java programs are allowed to access different inputs and outputs in the same way through the stream.

2. stream classification

Input stream and output stream 

A. input stream: Only data can be read from it, but data cannot be written into it.

B. output stream: Only data can be written into the table, but not data can be read.

It can be understood that data, from memory to hard disk, is usually considered as an output stream, that isWrite operationOn the contrary, from hard disk to memory, it is usually regarded as an input stream, that is, a read operation. The input and output here areFrom the memory perspective.

The input stream of Java mainly includes InputStream and Reader as the base class, while the output stream mainly uses OutputStream and Writer as the base class;

 

Byte stream and byte stream

The difference between byte streams and byte streams is very simple, and their usage is almost the same. The difference is that the data units operated by the byte stream and the byte stream are different: the minimum unit of data operated by the byte stream is 8 bytes, while the byte stream is 16 bytes.

Byte streams are mainly composed of InputStream and OutputStream as the base class, while bytes streams are mainly composed of Reader and Writer as the base class.

Node stream and processing stream

Based on the role of the stream, it can be divided into node streams and stream processing.

It can read and write data streams from and to a specific IO device. It is called a node Stream, and the node Stream is often used as a Low-Level Stream)

Stream processing is used to encapsulate a connection to an existing stream, and then implement the data read/write function through encapsulation. A stream is called an advanced stream;

When a stream is used for input and output, the program does not directly connect to the actual data source and is not connected to the actual input and output nodes. An obvious advantage of stream processing is that the program can use the same input and output code to access different data sources as long as the same stream is used, the data source actually accessed by the program also changes as the stream of the processing stream lock package node changes.

The stream processing function mainly involves two aspects:

Performance Improvement: It mainly increases the input and output efficiency by adding buffering methods.

Convenient operation: stream processing may provide a series of convenient methods to input and output a large volume of content at a time, rather than inputting or outputting one or more units of data.

Processing streams can be "grafted" on the basis of any existing stream, which allows Java applications to access different input and output device input streams in the same code and transparent manner.

Byte input streamInputStreamAnd character input streamReader

InputStream and Reader are the base classes of all input streams. They are two abstract classes and cannot create instances to execute input. However, they have input stream templates, therefore, their methods are available for all input streams and output streams.

Common Methods in InputStream:

Int read (): read a single user from the input stream

Int read (byte [] B): reads a maximum of B. length bytes from the input stream, stores the read bytes in array B, and returns the actual number of bytes read.

Int read (byte [] B, int off, int len): reads a maximum of len bytes of data from the input stream, stores the data in number B, and puts it into array B, instead of starting from the array, it starts from the off position and returns the actual number of bytes read.

Frequently used methods in Reader:

Int read (): read a single character from the input stream

Int read (char [] c): reads data of up to c. length characters from the input stream, stores the data in character array c, and returns the actual read characters.

Int read (char [] c, int off, int len): reads data of up to len characters from the input stream, and stores the read data in character array c, read from the off of the array;

InputStream and Reader also support the following methods to move pointers:

Void mark (int readAheadLimit): The first mark (mark) at the current position of the record pointer)

Boolean markSupported (): determines whether the input stream supports the mark () operation, that is, whether record marking is supported.

Void reset (): relocates the record pointer of this stream to the mark position of the previous record.

Long skip (long n): records the n Bytes and characters that the pointer moves forward.

OutputStreamByte output stream andWriterCharacter output stream

You can use the following methods:

Void write (int c): The specified bytes and characters are output to the output stream.

Void write (byte []/char [] buf): transfers data from byte arrays/character arrays to the specified output stream.

Void write (byte []/char [] buf, int off, int len): outputs data from the specified array to the specified output stream.

The following methods are available for character output streams:

Void write (String s): outputs the specified String to the specified output stream.

Void write (String s, int off, int len): outputs the byte and character arrays starting from the off position and in The len Length to the output stream.

3. Java input and output streams:

Category

Byte input stream

Byte output stream

Character input stream

Character output stream

Abstract base class

InputStream

OutputStream

Reader

Writer

Access Files

FileInputStream

FileOutputStream

FileReader

FileWriter

Access Array

ByteArrayInputStream

ByteArrayOutputStream

CharArrayReader

CharArrayWriter

Access MPs queue

PipedInputStream

PipedOutputStream

PipedReader

PipedWriter

Access string

   

StringReader

StringWriter

Buffer stream

BufferedInputStream

BufferedOutputStream

BufferedReader

BufferedWriter

Conversion stream

   

InputStreamReader

OutputStreamWriter

Object stream

ObjectInputStream

ObjectOutputStream

   

Abstract base class

FilterInputStream

FilterOutputStream

FilterReader

FilterWriter

Print stream

 

PrintStream

 

PrintWriter

Push back the input stream

PushbackInputStream

 

PushbackReader

 

Special stream

DataInputStream

DataOutputStream

   

Input and output stream systems:

Push back the input stream:

Two special streams are distinctive, namely PushbackInputStream and PushbackReader. They have the following common methods:

Void unread (byte []/char [] buf): pushes a byte/character array to the buffer, and reads the pushed content repeatedly.

Void unread (byte []/char [] buf, int off, int len): reads a byte/character array from the off position, the content of the string/byte array with the length of len is pushed back to the buffer, and the content just read can be repeated.

Void unread (int B): pushes a byte and character back to the buffer zone.

The two push-back input streams have a buffer zone. When the program calls unread, the system will push the content of the specified array back to the buffer zone, and push-back the input stream to call the read method each time, the content in the push back buffer will always be read first. The content in the original input stream will be read only after the content in the buffer is fully read and not filled with the array required for read;

Redirect standard input/output

There are three standard input and output methods in System:

Static void setErr (PrintStream e): redirects the "standard" error output stream

Static void setIn (InputStream in): redirects the "standard" input stream

Static void setOut (OutputStream out): redirects the "standard" output stream.

JVM writes data from other processes

The Runtime object has the exec method. It can run the jvm command line to generate a Process object. The Process object represents the sub-Process started by the Java program. The Process class has the following methods, can communicate with sub-processes;

InputStream getErrorStream (): gets the error stream of the sub-process

InputStream getInputStream (): gets the input stream of the sub-process.

OutputStream getOutputStream (): gets the input stream of the sub-process.

4. RandomAccessFile

RandomAccessFile is the file content handler class with the most abundant functions in the Java Input and Output systems. It provides many methods to access the file content. It can read the file content or output data like a file. Unlike normal input and output streams, OSS operates file data in a random access mode.

RandomAccessFile can be used to position file pointers freely. Therefore, RandomAccessFile can be output without starting from. RandomAccessFile can append content to an existing file.

The RandomAccessFile object contains a pointer to record the current read/write location. When the program creates a new RandomAccessFile object, the pointer is in the file header, which is both 0; after reading or writing n Bytes, the file Pointer Points to the last position. In addition, the file pointer can be moved freely. RandomAccessFile has the following methods to operate the pointer:

Long getFilePointer (): returns the current position of the file record pointer.

Void seek (long pos): locates the file record pointer to the pos position.

RandomAccessFile can be read or written, so it contains a read method similar to InputStream, And the write method of OutputStream. Its usage is the same as that of the original one; randomAccessFile also contains the input and output methods of readXxx and writeXxx;

File Access Mode of RandomAccessFile:

R: open a specified file in read-only mode

Rw: opens a specified file in read or write mode. If the file does not exist, it is created.

Rws: opens a specified file in Read and Write mode. In the rw mode, each update of the file content and metadata must be synchronized to the underlying storage device.

Rwd: open a specified file in read/write mode. For rw, each update of the file content must be synchronized to the underlying device.

5. serialization

Serialization is often used in remote calls and distributed development. It stores java object serialized files and deserializes them during parsing. The Serializable interface must be used; objects that implement this interface can be serialized into a file and saved on the hard disk. deserialization also finds this object through the interface id.

Transient can ignore the fact that an attribute in an object is not serialized.

6NewNIO

Introduction to commonly used nio packages:

Java. io package: mainly provides Buffer-related classes.

Java. io. channels: including related classes of Selector and Channel

Java. nio. charset: Contains classes related to character sets.

Java. nio. channels. spi: Provides the Channel service class

Java. nio. charset. spi: Provides the text set service class

Buffer Introduction

Buffer is the container for data extraction. Here there are ByteBuffer, CharBuffer, protocol Buffer, IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer.

In addition to ByteBuffer, the above classes use similar methods to manage data, except that the data types managed by them are different. There is no constructor for these buffers. You can use the following method to obtain a Buffer object:

Static XxxBuffer allocate (int capacity) creates a XxxBuffer object with capacity of capacity.

ByteBuffer subclass MappedByteBuffer, which is used to indicate that Chanael maps part or all of the hard disk files to the memory for the result. Generally, the MappedByteBuffer object is returned by the map method of Chanael.

Buffer has three important concepts: capacity, limit, and position)

Capacity: The Buffer capacity indicates the maximum data capacity of the Buffer, that is, the maximum amount of data that can be stored. The Buffer capacity cannot be negative, it cannot be changed after creation.

Limit: The first index of the buffer location that should not be read or written. That is to say, the data after the limit cannot be read or written.

Position: Specifies the index of the buffer location written by the next readable latter. Similar to the record pointer position in the IO stream. When a new Buffer object is created, the container position is 0. If two data is read from the Channel to the Buffer, the postion is 2, pointing to the third Buffer object.

Common Buffer methods:

Int capacity (): returns the Buffer capacity.

Boolean hasRemaining (): determines whether there are any elements between the current position and the limit for processing.

Int limit: return the location of the Buffer limit (limit ).

Buffer limit (int newLimit) resets the Boundary Value and returns an object with a new limit Buffer.

Buffer mark (): sets the mark position of the Buffer. It can only mark between 0 and position.

Int position (): returns the position of the current Buffer.

Buffer postion (int newPostion): sets a new location of the Buffer and returns a Buffer object with a new limit.

Int remaining (): returns the number of elements between the current position and the limit.

Buffer reset (): Set the position to the mark position.

Buffer rewind (): sets the position to 0 to cancel the set mark.

When put and get are used to access data in the Buffer, they are divided into two types: absolute and relative:

Relative: reads and writes data from the current position in the Buffer, and then adds the position value to the number of processing elements.

Absolute: reads or writes data directly to the Buffer according to the index, and uses an Absolute method to access the data of the Buffer mechanism without affecting the position value.

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.