Java advanced ------ IO stream

Source: Internet
Author: User

Java advanced ------ IO stream

 

Concept and basic classification of stream: Concept of stream:

Stream is a very visual concept. When the program needs to read data, it will open a stream to the data source, which can be a file, memory, or network connection. Similarly, when the program needs to write data, it will open a stream to the destination. At this time, you can imagine that the data is "Flowing" here ".

Stream classification:

By data: input stream and output stream

Input stream: InputStream/Reader

Output stream: OutputStream/Writer

By data type: byte stream and byte stream

Byte stream: InputSteam/OutputStream

Internal stream: Reader/Writer

Differences between byte stream and byte stream:

1. When a byte stream is read, a byte is returned when a byte is read. When the byte stream reads one or more bytes (two bytes for the Chinese character, three in the UTF-8 code table), first query the specified encoding table, returns the characters found.

2. byte streams can process all types of data, slices, and mp3 files. The character stream can only process character data.

3. The input streams of the byte stream end with InputStream, and the output streams of the byte stream end with OutputStream. The InputStream or OutputStream represents the role of the stream. The input stream of the upstream stream ends with Reader, and the output stream of the upstream stream ends with WriterStream. the same stream and the former part of the byte stream also represent the role of the stream. In fact, byte streams do not use the buffer itself during operations, but directly operate on the file itself. However, the swap stream uses the buffer during operations and can operate on files through the buffer.

Note: As long as it is plain text data, the use of the bytes stream should be given priority. In addition, byte streams should be used.

Common stream: byte input stream:

The InputStream class is the parent class of all byte streams.

Three basic read () methods:

Int read (); // read a byte from the stream. It is not recommended.

Int read (byte [] B); // read data into the byte array and return the number of bytes read.

Int read (byte [] B, int off, int len); // The number of bytes from which len reads data. Reads a maximum of len data bytes at the off position in the input stream into the byte array.

Other common methods:

Void close (); // close the input stream and release all system resources associated with the stream.

Int available (); // returns the number of bytes read from the input stream without blocking.

Long skip (long n); // skip and discard n data bytes in the input stream. This method may be invalid.

Boolean markSupported (); // test whether the input stream supports the mark and reset methods.

Void mark (int n); // mark the current position in the input stream.

Void reset (); // locate the stream again when the mark method is called for the input stream.

Byte output stream:

The OutputStream class is the parent class of all byte output streams.

Three basic write () methods.

Void write (int n); // write the specified byte to this output stream.

Void write (byte [] B); // write B. length bytes from the specified byte array to this output stream.

Void write (byte [] B, int off, int len); // write the len bytes starting from offset off in the specified byte array to this output stream.

Other common methods:

Void close (); // close the output stream and release all system resources related to the stream.

Void flush (); // refresh the output stream and forcibly write all buffered output bytes.

File input and output streams:

FileInputStream and FileOutputStream

To construct a FileInputStream, the associated file must exist and be readable. For example:

FileInputStream FCM = new FileInputStream ("myfile. dat ");

To construct a FileOutputStream, and if the output file already exists, it will be overwritten. For example:

FileOutputStream fos = new FileOutputStream ("result. dat ");

If you want to write files in append mode, you need a parameter:

FileOutputStream fos = new FileOutputStream ("result. dat", true); // If the parameter is true, the append method is used for output. If the parameter is false, the same method is used for output.

Ghost stream:

Reader and Writer are the parent types of all slave streams.

Java uses Unicode to represent strings and characters, and provides a 16-bit stream to process characters in a similar way.

Bridge stream:

InputStreamReader and OutputStreamWriter (bridge converter for converting byte streams)

These two classes are not used for direct input and output. They convert byte streams into the bridge converter of the dense stream and can specify the encoding/decoding method.

Row-by-row read/write stream:

Both of the above are filter streams, and other node streams must be used as parameters to construct objects.

BufferedReader method: String readLine (); // when its return value is null, the read is complete. Pay attention to writing line breaks when writing again. Otherwise, blocking may occur.

BufferedWriter method: newLine (); this method will write a line break.

Pipeline Flow:

Used for thread interaction.

PipedInputStream/PipedOutputStream transfers the output stream to the input stream to create a communication pipeline. The output stream is the sender of the MPs queue. Generally, data is written to the PipedOutputStream object by a thread and read from the connected PipedInputStream by other threads.

Note: The pipeline output stream and the pipeline input stream need to be connected.

Data Stream:

DataInputStream and DataOutputStream; read and write Basic Java classes through streams. Note that the methods of DataInputStream and DataOutputStream are paired. Supports direct output of various data types.

Note: when using these two classes, you must note that the write order is the same as the read order. Otherwise, the information not separated and written will be incorrectly split and the wrong data will be read.

 

Object stream:

ObjectInputStream and ObjectOutputStream (Object serialization ). Object stream is a filter stream. It requires a node stream as a parameter to construct an object, which is used to directly write the object into a file and read the object from the file.

Only objects of the Serializable interface type can be read and written. The Serializable interface is a tag interface, and no method is defined.

The object will serialize a binary code and save the object attributes in the file.

WriteObject (o) and readObject () are the methods used for object read/write operations. For example:

If there are other types of objects in a class, this class implements the Serializable interface. During Object serialization, attributes in this class are also required to be able to serialize objects.

Note:

For object stream operations, it is necessary to write the object at one time. If you use the append mode to write the object, only the object written in the previous time will be read. When you use the object stream to write the object, first, a header is written, then data is written, and the end symbol is added. If you use the append method to write data, the end symbol is written downward, however, only the ending character is read, and data written again in the future will be lost.

The package name, class name, and attribute can be serialized. Methods and constructors are not serialized.

Static attributes are not serialized.

The property will be recursively serialized, that is, a class has a property of the reference type. If the class corresponding to this property implements the Serializable interface, during Object serialization, it also serializes the attributes of this class.

The following uses an example to demonstrate the usage of the above various streams:

IODemo. java

 

Package com. jesson. mianshi. io; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. fileReader; import java. io. fileWriter; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import ja Va. io. objectInputStream; import java. io. objectOutputStream; import java. io. outputStreamWriter; import java. io. pipedInputStream; import java. io. pipedOutputStream; import java. io. reader; import javax. sound. sampled. line; import org. w3c. dom. CDATASection; public class IODemo {private final static String path = ". /testRead. dat "; private static FileInputStream FCM; private static FileOutputStream fos;/*** @ param Args */public static void main (String [] args) {// TODO Auto-generated method stub // test the read method byteReadFun (); // test the write method byteWriteFun (); // test the FileReader method charReaderFun (); // test the bridge stream bridgeStream (); // test the row-by-row read/write stream bufferedFun (); // test the data stream dataStream (); // test object stream objectStream (); // test pipeline stream pipeFun ();} /*** test the three read methods of the byte input stream and some other common methods */private static void byteReadFun () {try {/*** method 1. read one byte at a time, read the entire file and we can see that the efficiency is very low */fs = new Fi LeInputStream (path); int readByte = Fi. read (); while (readByte! =-1) {System. out. print (readByte); readByte = Sox. read ();} fiis. close (); System. out. println ("\ n Bytes");/*** method 2, each time the specified size bytes are retrieved into the array, where, the size of the array can be specified at will */fiis = new FileInputStream (path); byte [] B = new byte [100]; while (fiis. read (B )! =-1) {for (int I = 0; I <B. length & B [I]! = '\ 0'; I ++) {System. out. print (B [I. close (); System. out. println ("\ n Bytes");/*** method 3: Read the specified size bytes to the array each time, and specify the initial position and length of the written array, the size of the array can be specified at will */fiis = new FileInputStream (path); byte [] b1 = new byte [100]; fiis. read (b1, 0, 20); for (int I = 0; I <b1.length; I ++) System. out. print (b1 [I]); FCM. close (); System. out. println ("\ n ------ Tests ");/*** test the use of the skip, mark, and rest Methods */fiis = new FileInputStream (path); fiis. skip (9); int len = 10; while (len --> 0) {System. out. print (FCM. read ();} // test whether the mark and reset methods are supported. out. println ("\ n supports mark and reset:" + FS. markSupported (); System. out. println ("--------------------------------------------------------------------------- -------------- ");} Catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}/ *** Test Three write methods of the byte output stream and other common methods */private static void byteWriteFun () {try {/*** Method 1: Write the specified byte to this output stream */fos = new FileOutputStream (". /testWrite. dat "); fos. write (20);/*** Method 2: Set the specified B. length bytes are written to the output stream from the specified byte array */String OutString = "Hello world! "; Byte [] B = outString. getBytes (); fos. write (B);/*** method 3: write len bytes starting from offset off in the specified byte array to this output stream */String outString2 = "Hello jesson! "; Byte [] b2 = outString2.getBytes (); fos. write (b2, 4, 5); fos. close ();/*** Method 4: If you want to write data to the same file in append mode, a parameter is required and the default value is false, add */fos = new FileOutputStream (". /testWrite. dat "); fos. write (1, 200); fos. flush (); // refresh the output stream and forcibly write all buffered output bytes fos. close (); // close the output stream and release the system resource fos = new FileOutputStream (". /testWrite. dat ", true); String outString3 =" Hello java! "; Fos. write (outString3.getBytes (); fos. flush (); fos. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}/ *** character input/output stream test */private static void charReaderFun () {try {FileWriter fWriter = new FileWriter (". /testWriter. dat "); fWriter. write ("Hello, java, hello io! \ N "); fWriter. close (); FileReader fileReader = new FileReader (". /testWriter. dat "); char [] cbuf = new char [50]; int len = fileReader. read (cbuf); System. out. println (new String (cbuf, 0, len); fileReader. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("success ("-----------------------------------------------------------------------------------------");}/*** Bridge stream, that is, InputStreamReader and OutputStreamWriter */private static void bridgeStream () {try {FD = new FileInputStream (path); InputStreamReader isr = new InputStreamReader (FCM ); char [] cbuf = new char [100]; isr. read (cbuf); System. out. println (cbuf); isr. close (); FCM. close (); fos = new FileOutputStream (". /testWrite. dat "); OutputStreamWriter osw = new OutputStreamWriter (fos); osw. write ("good night! \ N "); osw. close (); fos. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("bytes");}/*** row-by-row read/write stream: BufferedReader and BufferedWriter */private static void bufferedFun () {try {FileWr Iter fWriter = new FileWriter (". /testWriter1.dat "); BufferedWriter bWriter = new BufferedWriter (fWriter); bWriter. write ("Hello, this is a row-by-row read/write stream"); bWriter. newLine (); bWriter. write ("BufferedWriter"); bWriter. newLine (); bWriter. close (); fWriter. close (); FileReader fReader = new FileReader (". /testWriter1.dat "); BufferedReader bReader = new BufferedReader (fReader); String line = bReader. readLine (); while (line! = Null) {System. out. println (line); line = bReader. readLine () ;}} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("Pipeline");}/*** test pipeline stream, mainly used for thread interaction */private static void pipeFun () {System. out. println ("pipeline flow test"); try {PipedInputStream pis = new PipedInputStream (); PipedOutputS Tream pos = new PipedOutputStream (); pis. connect (pos); new Thread (new ReadThread (pis )). start (); new Thread (new WriteThread (pos )). start ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}/*** read thread *** @ author jesson **/static class ReadThread implements Runnable {PipedInputStream pis; public ReadThread (PipedInputStream pis) {// TODO Auto-generated constructor stubthis. p Is = pis ;}@ Overridepublic void run () {// TODO Auto-generated method stubtry {byte [] buf = new byte [1024]; System. out. println ("before reading ...... no data ...... blocking "); int len = pis. read (buf); System. out. println ("read data ...... blocking ends "); String s = new String (buf, 0, len); System. out. println (s); pis. close ();} catch (IOException e) {throw new RuntimeException ("Pipeline failed to read stream");} System. out. println ("------------------------------------- Pipeline ") ;}}/*** write thread ** @ author jesson **/static class WriteThread implements Runnable {PipedOutputStream pos; public WriteThread (PipedOutputStream pos) {// TODO Auto-generated constructor stubthis. pos = pos ;}@ Overridepublic void run () {// TODO Auto-generated method stubtry {System. out. println ("starts to write data, wait 6 seconds later. "); Thread. sleep (6000); pos. write ("hello pipeS Tream! \ N ". getBytes (); pos. close ();} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}/ *** test data stream */private static void dataStream () {Member [] members = {new Member ("jesson", 24 ), new Member ("cherry", 23), new Member ("john", 32)}; System. out. println ("Test Data Stream"); System. out. println ("data before operation"); // output the restored data for (Member member: members) {System. out. printf ("% s \ t % d \ n", member. getName (), member. getAge ();} try {DataOutputStream dos = new DataOutputStream (new FileOutputStream ("testDataStream.txt"); for (Member member: members) {dos. writeUTF (member. getName (); dos. writeInt (member. getAge ();} // write all data to the destination dos. flush (); dos. close (); DataInputStream dis = new DataInputStream (new FileInputStream ("testDataStream.txt"); for (int I = 0; I <members. length; I ++) {String name = dis. readUTF (); int age = dis. readInt (); members [I] = new Member (name, age);} dis. close (); System. out. println ("restored data"); // output the restored data for (Member member: members) {System. out. printf ("% s \ t % d \ n", member. getName (), member. getAge () ;}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("tests");}/*** test object stream */private static void objectStream () {System. out. println ("test Object stream"); try {ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("testObject.txt"); object Object object = new Student ("James", 25, ""); oos. writeObject (object); oos. close (); ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("testObject.txt"); Student student = (Student) ois. readObject (); ois. close (); System. out. println (student. getName () + "\ t" + student. getAge () + "\ t" + student. getSchool ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("success ("-----------------------------------------------------------------------------------------");}}

 

When testing the data stream, the Member class is used.

Member. java

 

package com.jesson.mianshi.io;public class Member {private String name;private int age;public Member() {// TODO Auto-generated constructor stub}public Member(String name,int age){this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
The serialization class is used during object stream testing.

 

Student. java

 

Package com. jesson. mianshi. io; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. io. serializable;/*** serialize this class for transmission and storage. * @ author jesson **/public class Student implements Serializable {private String name; private int age; private String school; public Student () {// TODO Auto-generated constructor stub} public Student (String name, int age, String school) {this. name = name; this. age = age; this. school = school;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String getSchool () {return school;} public void setSchool (String school) {this. school = school;}/*** defines the writeObject method and writes the object into the stream for Object Persistence * @ param out */private void writeObject (ObjectOutputStream out) {try {out. writeUTF (name); out. writeInt (age); out. writeUTF (school);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}/ *** defines the readObject method, which is used to read the object * @ param in */private void readObject (ObjectInputStream in) {try {name = in. readUTF (); age = in. readInt (); school = in. readUTF ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
    

 

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.