Java Io stream knowledge Summary

Source: Internet
Author: User
Tags object serialization

Conclusion 1:

General Usage principles of Java IO:

1. Classification by data source (destination:

1. File: fileinputstream, fileoutputstream, filereader, filewriter

2. byte []: bytearrayinputstream, bytearrayoutputstream

3. Char []: chararrayreader, chararraywriter

4. String: stringbufferinputstream, stringreader, stringwriter

5. network data streams: inputstream, outputstream, reader, and writer

Ii. formatted output score:

1. output to be formatted: printstream, printwriter

Iii. cache score:

1. Buffer: bufferedinputstream, bufferedoutputstream, bufferedreader, bufferedwriter

Iv. Data Format:

1. binary format (as long as it cannot be determined that it is plain text): inputstream, outputstream and all its sub-classes with stream termination

2. plain text format (including English letters, Chinese characters, and Other encoding methods); reader, writer, and all subclasses with reader and writer

5. Input/Output score:

1. Input: reader, a subclass of the inputstream type

2. Output: a subclass of the writer and outputstream types.

6. Special needs:

1. Conversion class from stream to reader: inputstreamreader and outputstreamwriter

2. Object input and output: objectinputstream and objectoutputstream

3. inter-process communication: pipeinputstream, pipeoutputstream, pipereader, and pipewriter

4. Merge input: sequenceinputstream

5. Special requirements: pushbackinputstream, pushbackreader, linenumberinputstream, and linenumberreader

 

The general guidelines for deciding which class to use and its construction process are as follows (special requirements are not considered ):

First, consider what is the original data format: Is it text?

Second, is it input or output?

Third, do you need to convert the stream: inputstreamreader and outputstreamwriter?

Fourth, what is the data source (destination): a file? Memory? Network?

Fifth, whether to buffer data: bufferedreader (Note: It is important to note whether Readline () is defined, and what are the more special input or output methods than read and write)

Sixth, do you want to format the output: print?

 

 

Conclusion 2:

 

The first is Java Io. This is really troublesome. I/O class libraries often use the abstraction of "stream. The so-called "stream" is an object that can generate or accept data and represents the source and target of the data. The stream hides the specific operations inside the I/O device. As shown in the JDK document, Java I/O class libraries are divided into two parts: input and output. All the derived classes of inputstream and reader have a basic inherited read () method that can read a single or byte array. Similarly, all the derived classes of outputstream and writer have a basic write () method that can write a single or byte array. But in general, you will not use these methods; they are used for other classes -- and the latter will provide some more practical interfaces. Therefore, you rarely encounter a situation where only one class can be used to create a stream. In fact, you have to fold multiple objects to obtain the required functions. The main reason why Java's stream class library is so confusing is that "you must use multiple objects to create a stream ".


Java Io class structure:
The Root Interface is inputstream/outputstream. The IO classes acting as data sources include fileinputstream/fileoutputstream, Bytes/bytearrayoutputstream, etc. The IO classes acting as decorative functions include bufferedinputstream/inputs, and datainputstream,
They all inherit from the decoration interface filterinputstream/filteroutputstream.
When I/O is used, create a data source I/O first, and then create a decoration class I/O Based on the required functions. The constructor parameter is the created data source I/O.
Taking the creation of a buffer file input stream as an example, assume that the file "C:/log.txt" needs to be read from the disk ":
// Create a fileinputstream:
Fileinputstream fileinput = new fileinputstream ("C: // log.txt ");
// Create a bufferedinputstream:
Bufferedinputstream bufferedinput = new bufferedinputstream (fileinput );
// The obtained bufferedinput is a buffer file input stream.
Or, you can simply enter the following:
Inputstream input = new bufferedinputstream (New fileinputstream ("C: // log.txt "));
// The input obtained now is a buffer file input stream.

 

Differences between Java. Io. Reader and Java. Io. inputstream
Java. Io. Reader and Java. Io. inputstream constitute JAVA input classes. Reader is used to read 16 characters, that is, Unicode-encoded characters. inputstream is used to read ASCII characters and binary data.
In Java, different types of Reader Input streams correspond to different data sources:
Filereader is used for input from a file;
Chararrayreader is used to input character arrays from the program;
Stringreader is used to input strings from the program;
Pipedreader is used to read data written to the pipeline from pipedwriter in another thread.
Different types of inputstream input streams correspond to different data sources: fileinputstream, bytearrayinputstream, stringbufferinputstream, and pipedinputstream. In addition, there are two inputstream input streams that do not have the corresponding Reader Type:
Socket is used for sockets;
Urlconnection is used for URL Connection.
These two classes use getinputstream () to read data.
Correspondingly, there are similar differences between Java. Io. Writer and Java. Io. outputstream.


1. Java technology supports two data types of streams
Inputstream and outputstream: byte stream. Other byte streams are subclasses of inputstream or outputstream.
Reader and Writer: Internal stream. Other streams are subclasses of reader or writer.


2. node stream
Java 2 SDK has three basic types of nodes: file, memory, and pipe ).


3. Process Flow
Process streams are placed above other streams to complete sorting, transformation, and other operations. A process stream is also called a filter stream.
When you need to change the original data of the input stream, you can connect a filtered input stream to an original input stream.
Use a filter stream to convert the raw data into the format you need.

4. Basic byte streams
4.1. fileinputstream and fileoutputstream
These two node streams are used to manipulate disk files. Constructors of these classes allow you to specify the files they are connected.
To construct a fileinputstream, the associated file must exist and be readable.
If you want to construct a fileoutputstream and the output file already exists, it will be overwritten.
Fileinputstream infile = new fileinputstream ("myfile. dat ");
Fileoutputstream OUTFILE = new fileoutputstream ("results. dat ");
4.1 bufferinputstream and bufferoutputstream
These are filter streams, which can improve the efficiency of I/O operations.
4.3. pipedinputstream and pipedoutputstream
The pipeline stream is used for communication between threads. The pipedinputstream object of one thread reads the input from the pipedoutputstream object of another thread.
To make the pipeline stream useful, you must have an input party and an output party.
4.4. datainputstream and dataoutputstream
These filters read and write Basic Java classes through streams

5. Basic streams
The figure illustrates the architecture of reader and writer internal streams.
5.1. inputstreamreader and outputstreamwriter
This interface is used to convert byte streams to byte streams.
When you construct an inputstreamreader or outputstreamwriter, the conversion rules define the conversion between the 16-bit Unicode and the specific representation of other platforms.
Inputstreamreader reads bytes from a data source and automatically converts them to unicode characters.
If you specifically declare that inputstreamreade will replace byte streams with other types of bytes streams.
Outputstreamwriter writes the Unicode encoding of characters to the output stream. If you are not using Unicode characters, outputstreamwriter converts your character encoding to unicode encoding.
5.2. Buffer readers and authors
Because the conversion between different formats is similar to other I/O operations, the maximum efficiency of processing large data blocks is reached.
It is a good idea to link a bufferedreader and bufferedwriter at the end of inputstreamreader and outputstreamwriter.
Remember to use the flush () method for bufferedwriter.
5.3 use other characters for conversion
If you need to read the input from a non-local character code (for example, from a network connection to a different type of machine,
You can use explicit character encoding to construct IR = new inputstreamreader (system. In, "8859_1") Like the following program ″);
Note: If you read characters through a network connection, you should use this form.
Otherwise, your program will always try to convert the characters read as a local representation, which is not always correct. ISO 8859-1 is the Latin-1 encoding mode mapped to ASCII.

6. Object serialization
The Java. Io. serializable interface supports storing a Java technical object in a stream.
Storing an object in a type of permanent storage is called "persistence ".
If an object can be stored on a disk or tape, or can be sent to another machine and stored in a storage or disk, the object is called a retainable object.
The Java. Io. serializable interface does not have any method. It serves only as a "mark" to indicate that the classes that implement this interface can be serialized.
Objects that do not implement the serializable interface in the class cannot be kept.
// Append an object:
// The second parameter in filewriter () indicates whether to Append content to the file.
Printwriter out = new printwriter (New filewriter (logfilename, true), true );
The most common classes for reading and writing files in Java are fileinputstream/fileoutputstream and filereader/filewriter.
Fileinputstream and fileoutputstream are based on byte streams and are often used to read and write binary files.
We recommend that you use character-based filereader and filewriter to read and write character files, eliminating the need for conversion between bytes and characters.
However, the constructors of these two classes use the system encoding method by default. If the file content is inconsistent with the system encoding method, garbled characters may occur.
In this case, we recommend that you use the parent class of filereader and filewriter: inputstreamreader/outputstreamwriter,
They are also character-based, but the constructor can specify the encoding types: inputstreamreader (inputstream in, charset CS) and outputstreamwriter (outputstream out, charset CS ).

 

 

// Read/write file encoding:
Inputstreamreader r = new inputstreamreader (New fileinputstream (filename), "UTF-8 ″);
Outputstreamwriter out = new outputstreamwriter (New fileoutputstream (filename), "UTF-8 ″);

 

/**
Comparison of Three Types of Io performance:
When reading and writing a 10 K file, the three methods take the following time:
Inputstreamreader and outputstreamwriter: 63 MS (file encoding can be set, if no buffer is needed)
Bufferedreader and bufferedwriter: 31 Ms
Bufferedinputstream and bufferedoutputstream: 16 Ms
*/

 

/**
* Description: test the Java Io's efficiency
* Author: allancao
* Date: 2007-02-18
*/
Import java. Io .*;

/**
*Using the inputstreamreader and outputstreamwriter
*/
Class encoderrw {
Public static string read (string filename) throws ioexception {
Stringbuffer sb = new stringbuffer ();
/* Buffer is used for file reading. If no buffer is used, the performance will be doubled */
Bufferedreader in = new bufferedreader (New inputstreamreader (New fileinputstream (filename), "UTF-8 ″));
String S;
While (S = in. Readline ())! = NULL ){
SB. append (s );
SB. append ("/N ");
}
In. Close ();
Return sb. tostring ();
}
Public void write (string filename, string text) throws ioexception {
Outputstreamwriter out = new outputstreamwriter (New fileoutputstream (filename), "UTF-8 ″);
Out. Write (text );
Out. Flush ();
Out. Close ();
}
}

 

/**
*Using the bufferedreader and bufferedwriter
*/
Class writerreader {
Public String read (string filename) throws ioexception {
Stringbuffer sb = new stringbuffer ();
Bufferedreader in = new bufferedreader (New filereader (filename ));
String S;
While (S = in. Readline ())! = NULL ){
SB. append (s );
SB. append ("/N ");
}
In. Close ();
Return sb. tostring ();
}
Public void write (string filename, string text) throws ioexception {
Printwriter out = new printwriter (New bufferedwriter (New filewriter (filename )));
Out. Print (text );
Out. Close ();
}
}

 

/**
*Using the bufferedinputstream and bufferedoutputstream
*/
Class bufferedstream {
Public byte [] Read (string filename) throws ioexception {
Bufferedinputstream remotebis = new bufferedinputstream (New fileinputstream (filename ));
Bytearrayoutputstream baos = new bytearrayoutputstream (10240 );
Byte [] Buf = new byte [1, 1024];
Int bytesread = 0;
While (bytesread> = 0)
{
Baos. Write (BUF, 0, bytesread );
Bytesread = remotebis. Read (BUF );
}
Byte [] content = baos. tobytearray ();
Return content;
}
Public void write (string filename, byte [] content) throws ioexception {
Bufferedoutputstream out = new bufferedoutputstream (New fileoutputstream (filename ));
Out. Write (content );
Out. Flush ();
Out. Close ();
}
}

 

Public class testio
{
Public static void main (string [] ARGs) throws ioexception {
Long currenttime = system. currenttimemillis ();
Encoderrw RW = new encoderrw ();
RW. Write ("index. dat", RW. Read ("fileutil. Java "));
System. Out. println ("cost time:" + long. tostring (system. currenttimemillis ()-currenttime) + "Ms ");

Currenttime = system. currenttimemillis ();
Writerreader wR = new writerreader ();
Wr. Write ("index. dat", wR. Read ("fileutil. Java "));
System. Out. println ("cost time:" + long. tostring (system. currenttimemillis ()-currenttime) + "Ms ");

Currenttime = system. currenttimemillis ();
Bufferedstream BF = new bufferedstream ();
BF. Write ("index. dat", BF. Read ("fileutil. Java "));
System. Out. println ("cost time:" + long. tostring (system. currenttimemillis ()-currenttime) + "Ms ");
}
}

 

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.