IO stream in Java

Source: Internet
Author: User
Tags file copy serialization

One, Java streaming input/output principle

  

Stream is used to read and write data, Java has a class called file, it encapsulates the filename of the files, just an object in memory, the real file is a piece of space on the hard disk, in this file contains a variety of data, we want to read the data in the file what to do? is to read through a stream, we want to read from the program, for the computer, no matter what type of data is read in 010101101010 such form. How to read the data inside the file? You can think of the file as a small bucket, the file is a bucket, the data in the file is equivalent to the water inside the bucket, then how can we get water from the bucket, that is, how to read from this file data.

The common way to get water is that we use a pipe into the bucket above, and then open the faucet on the other side of the pipe, the water in the bucket starts crashing from the faucet, the water inside the bucket is flowing through this pipe, so this pipe is called flow, Java flow input/ The output is exactly the same as the flow, when you want to read data from a file, a pipe is inserted into the file, and then the data inside the file flows out of the pipeline, then you can read from the other end of the pipeline from the file flow out of a variety of data. When you want to write data to a file, it is also through a pipe, so that the data to be written through the pipeline crashed into the file. In addition to from the file to fetch data, but also through the network, such as with a pipe to connect me with your machine, I say a word, through this pipe flow into your machine inside, you can immediately see, and you say a word, through this pipe flow into my machine inside, I also immediately can see. Sometimes, a pipe is not enough, for example, the pipe flow through the water there are some impurities, we can in this root pipe outside a layer of pipe, the impurities to filter out. From the point of view of the program, the original data read from the computer must be 010101 of this form, one byte by one byte to read out, when you read this way you think this method is not appropriate, it's okay, you again in this pipe outside to wrap a more powerful pipeline, This pipe can convert 010101 to a string for you. This way you can read the data by using the program is no longer a 010101 of this form of data, but a number of things to understand the string.

Ii. input and output stream classification

The IO package defines all the streams, so a flow means that the IO packet

What is an input stream? What is an output stream? With one end of a pipe inserted into the program inside the file, and then start reading the data, is this input or output? If you stand in the angle of the file, this is called the output, if you stand in the angle of the program, this is called input.

  Remember that the input and output streams are all at the point of view of the program.

Third, node flow and processing flow

  

If you are not satisfied with the original flow, you can set another pipe outside this pipe, and the flow over the other pipe is called the flow of processing. Why do we need to process the flow? This is with the flow of impurities, you have to filter it, you can set a layer of pipe to filter these impurities.

3.1. Node stream type

  

A node stream is a pipe that plugs directly into the data source, reads data directly from the data source, or writes data directly to the data source. A typical node stream is a file stream: A file's byte input stream (FileInputStream), a file's byte output stream (FileOutputStream), a file's character input stream (FileReader), and a file's character output stream (FileWriter).

3.2. Process Flow Type

  

A process flow is a stream that is wrapped over another stream, which is the equivalent of a pipeline that is wrapped to another pipe.

Iv. InputStream (Input stream)

  

Some of the specific pipelines we see, those that end in InputStream, are entered into the data in bytes to our program.

The basic method of 4.1.InputStream

  

The read () method is a byte-by-byte read-out, one byte per byte, for each read. The read (byte[] buffer) method reads the data by filling in the array buffer of the byte[] type (buffer is a block of memory) and then processes the data inside the array. This is the same as we take the water, first with a bucket to pick up, wait for the bucket to fill the water before processing the water in the bucket. If you are processing one byte per byte read, it is too tired to read this way.

V, outputstream (output stream)

  

The basic method of 5.1.OutputStream

  

Vi. Reader Flow

  

The basic method of 6.1.Reader

  

Vii. writer Flow

  

The basic method of 7.1.Writer

  

Eight, the node flow explanation

This type of file is a typical representation of the node stream.

  

Example: using the FileInputStream stream to read the contents of a Fileinputstream.java file

1 package cn.galc.test; 2 3 Import java.io.*; 4 5 public class Testfileinputstream {6 public static void Main (String args[]) {7 int b = 0;//use variable b to install Invoke REA The D () method returns an integer of 8 fileinputstream in = null; 9//Use FileInputStream stream to read Chinese content, read out is garbled, because the InputStream stream inside the Read () method reads the content is a byte to read, and a Chinese character is occupied two bytes, So the reading of Chinese characters can not be displayed correctly. Ten//FileReader in = null;//both Chinese and English can display correctly when using the FileReader stream, because the read () method inside the reader stream is read one character at a time, so that each read is a complete Chinese character, which can be displayed correctly. try {in = new FileInputStream ("D:\\java\\myeclipse 10\\workspaces\\annotationtest\\src\\cn\\galc \\test\\FileInputStream. Java ");//in = new FileReader (" D:/java/io/testfileinputstream.java "); catch (filenotfoundexcep tion e) {System.out.println ("The system cannot find the specified file! "); System.exit (-1);//System exit}18 Long num = 0;//use variable num to record the number of characters read to the try {//Call R The EAD () method throws an exception, so you need to catch the exception ((b = In.read ())! =-1) {21//Call int read () throws Exception method, Returns an integer of type int 22//The condition of the end of the loop is to return a value of 1, indicating that the end of the file has been read at this time. +//System.out.print (b + "\ T");//If you do not use "(char) B" for conversion, then the direct printing of B is the number, not English and Chinese System.out             . Print ((char) b);//"char (b)" Converts Chinese and English letters using numbers to character input num++;27}28         In.close ();//Close input stream System.out.println (); System.out.println ("Read all" + num + "bytes"); 31 } catch (IOException E1) {System.out.println ("file read error! "); 33}34}35}

Example: Using a fileoutputstream stream to write data to a file

 1 package cn.galc.test; 2 3 Import java.io.*; 4 5 public class Testfileoutputstream {6 public static void Main (String args[]) {7 int b = 0; 8 Fil Einputstream in = null; 9 FileOutputStream out = null;10 try {One in = new FileInputStream ("D:\\java\\myeclipse 10\\wor Kspaces\\annotationtest\\src\\cn\\galc\\test\\mymouseadapter.java "); out = new FileOutputStream (" D:/java/Tes             Tfileoutputstream1.java "); 13//indicates the file to which the data is to be written, and if no testfileoutputstream1.java such a file exists in the specified path, the system will automatically create a 14              while ((b = In.read ())! =-1) {out.write (b); 16//Call the Write (int c) method to write all the characters read to the specified file 17             }18 in.close (); Out.close (); catch (FileNotFoundException e) {21             SYSTEM.OUT.PRINTLN ("file read failed"); System.exit (-1);//non-normal exit (IOException E1) {24 System.out.println ("File copy failed!       "); System.exit (-1); 26  }27 system.out28. println ("The contents of the Testfileinputstream.java file have been successfully copied into the file Testfileoutstream1.java"); 2 9}30}

Both FileInputStream and FileOutputStream are byte streams that are both input and output in a single unit of bytes. Therefore, the characters that occupy 2 bytes of storage space are displayed as garbled when they are read out.

Example: Writing data to a specified file using FileWriter (character stream)

 1 package cn.galc.test; 2 3/* writes data 4 to a specified file using FileWriter (character stream) write data in 1-character units/5 import java.io.*; 6 public class testfilewriter{7 public static void Main (String args[]) {8 */* use FileWriter output stream to write data from program to Uicode.da T files in 9 when writing data using FileWriter flow file is a character written by one character */10 FileWriter fw = null;11 try{12 FW = n                 EW FileWriter ("D:/java/uicode.dat"); 13//The nature of the character is an unsigned 16-bit integer 14//character occupies 2 bytes inside the computer 15 Here, we use a for loop to output all the integers in the 0~60000 16//This is equivalent to the whole world the text of each country is 0~60000 in the form of integers to represent the (int c=0;                     c<=60000;c++) {fw.write (c); 19//Use write (int c) to write an integer within the 0~60000 to the specified file 20 When I call the Write () method, I think that you should use "(char) C" for casting in the process of execution, that is, converting integers to characters to display 21//Because the file that is written to the data can be seen, the data displayed is not 0 An integer within a ~60000, but a representation of a different country's text 22}23/* Reads the contents of the specified file using FileReader (character stream) 24 reads in a single character.             int B = 0;26    Long num = 0;27 FileReader fr = null;28 FR = new FileReader ("D:/java/uicode.dat"); 29                     while ((b = Fr.read ())! =-1) {System.out.print (char) b + "\ T"); 31 Num++;32}33 System.out.println (); System.out.println ("Total read" +num+ "characters") ;}catch (Exception e) {e.printstacktrace (); 37}38}39}

Both the FileReader and FileWriter streams are character streams, both input and output in a single character unit. So read and write the 2-byte characters can be displayed normally, the above is the file type as an example of the node flow is explained, the so-called node flow specifies that the input stream or output directly into the data source, directly into the data source to write data or read data.

Ix. Processing Flow explanation 9.1. First processing stream-buffer stream (buffering)

   

Buffer is a small area in the memory, the data is read and write the data is first put into this buffer area, reduce the number of IO to the hard disk access, protect our hard disk. The buffer can be imagined as a small bucket, the data to be read and written into the water, each time the data read or write data before the data is loaded into the bucket, filled with the later to do processing. This is called a buffer. First put the data into the buffer, wait until the buffer is full, once again the buffer in the data written to the hard disk or read out, this can effectively reduce the number of access to the hard disk, is conducive to protect our hard disk.

Buffered stream test code:

 1 package cn.gacl.test; 2 3 Import java.io.*; 4 5 public class Testbufferstream {6 public static void Main (String args[]) {7 FileInputStream FIS = null; 8 try {9 FIS = new FileInputStream ("D:/java/testfileinputstream.java"); 10//In FILEINPUTST The outside of the ream node stream is a layer of processing flow BufferedInputStream11 Bufferedinputstream bis = new Bufferedinputstream (FIS);             NT C = 0;13 System.out.println ((char) bis.read ()); System.out.println ((char) bis.read ()); 15 Bis.mark (100);//Make a mark at the 100th character (int i = 0; I <= && (c = bis.read ())! =-1; i++) { System.out.print ((char) c);}19 System.out.println (); bis.reset ();//Return to the original marked place for (int i = 0; I <= && (c = bis.read ())! =-1; i++) {Sys Tem.out.print ((char) c),}24 Bis.close (), and the catch (FilenotfounDexception e) {e.printstacktrace (); (Exception E1) {e1.printstacktrace (); 2 9}30}31}
 1 package cn.gacl.test; 2 3 Import java.io.*;  4 public class testbufferstream1{5 public static void Main (String args[]) {6 try{7 BufferedWriter BW = new BufferedWriter (New FileWriter ("D:\\java\\dat.txt")); 8//outside the node stream filewriter a layer of processing flow BufferedWriter 9 String s = null;10 for (int i=0;i<100;i + +) {One s = string.valueof (Math.random ());//"Math.random ()" will generate a series of random numbers between 0~1. //static string valueOf (double D) The function of this valueOf () method is to convert the number of a double type to a string of//valueof () is a static method, you can use the form "type. static method name" to invoke Bw.write (s);//write the random number string to the specified file Bw.newline ();//Call NewLine ()  The method allows each write to a random number on a newline display of}17 bw.flush ();//Call Flush () method to empty the buffer. BufferedReader br =             New BufferedReader (New FileReader ("D:/java/dat.txt")); 20//a layer of processing flow outside the filereader of the node stream BufferedReader21 while ((s = br.readline ())!=null) {22//Use BuffThe Eredreader processing stream provides the string ReadLine () method to read the data in the file when a line reads 23///Loop End condition is that using the ReadLine () method to read the data returned by the null value of the string indicates that the file has been read to the At the end.          System.out.println (s);}27 bw.close (); Br.close (); 29 }catch (Exception e) {e.printstacktrace (); 31}32}33}

  

The input to the program refers to storing the content read from the file into the memory area allocated for the program. Flow, what is the flow, is nothing more than two pipes, a direction, a outward, to the outside are for our own writing procedures, flow into a variety of types, different classification methods can be divided into different types, according to the direction of the division, divided into the input stream and output stream, according to the unit of reading data, Can be divided into character stream and byte stream, in addition, can be divided into node stream and processing flow, the node flow is directly connected with the data source flow, processing flow is wrapped in other streams above the flow, processing flow is not directly connected to the data source, but from the data source read to the data after the processing stream processing again. The buffer stream also contains four classes: Bufferedinputstream, Bufferedoutputstream, BufferedReader, and BufferedWriter. Flow is a pair, no flow is not right, it must be a in, an out.

9.2. Second processing stream--conversion flow

  

The conversion stream is very useful, it can convert a byte stream into a character stream, there are two kinds of conversion flow, one called InputStreamReader, the other is called OutputStreamWriter. InputStream is a byte stream, reader is a character stream, InputStreamReader is to convert inputstream into reader. OutputStream is a byte stream, writer is a character stream, OutputStreamWriter is to convert OutputStream into writer. After converting the outputstream to writer, you can write the data in a single character through the pipeline, and you can also write the string. If we use a fileoutputstream to write something in a file, we have to write it one byte at a byte, but if we put a character conversion stream above the FileOutputStream stream, we can write a string in a string.

Conversion Stream Test Code:

 1 Package Cn.gacl.test, 2 3 import java.io.*; 4 5 public class TestTransform1 {6 public static void main (Stri Ng args[]) {7 try {8 OutputStreamWriter OSW = new OutputStreamWriter (9 new File             OutputStream ("D:/java/char.txt")), Osw.write ("Mircosoftsunibmoracleapplet");//write the string to the specified file 11  System.out.println (Osw.getencoding ());//Use the GetEncoding () method to obtain the default character encoding for the current system, Osw.close (); OSW = new OutputStreamWriter (New FileOutputStream ("D:\\java\\char.txt", True), "iso8859_1"); 15/ /If you do not add true when calling FileOutputStream's constructor, the newly added string replaces the string that was originally written, specifying the encoding of the character when the constructor method is called ("Mircosoftsunibmorac Leapplet ");//Writes a string to the specified file again, adding the newly written string to the back of the original string System.out.println (Osw.getencoding ()); Osw.clos E (); Exception} catch (e) {e.printstacktrace ();}23}24} 
1 package cn.gacl.test; 2  3 import java.io.*; 4 public class testtransform2{5 public     static void Main (String args[]) {6         try{7             in Putstreamreader ISR = new InputStreamReader (system.in); 8             //system.in Here is a standard input stream used to receive data from the keyboard input 9             bufferedreader br = new BufferedReader (ISR), and ten             String s = null; One             s = br.readline ();//Use the ReadLine () method to save a string of strings read to the string variable s (             s! = null) {                 System.out.println ( S.touppercase ());//print the string stored in memory s                 = Br.readline ();//continue to receive input from the keyboard from the inside of the Loop (                 s.equalsignorecase (" Exit ") {                     break;18                 }19             }20         }catch (Exception e) {             +///As long as the input exit loop ends E.printstacktrace ();         }23     }24}

9.3. Third processing stream-data flow

  

Data Flow Test Code:

 1 package cn.gacl.test; 2 3 Import java.io.*; 4 public class testdatastream{5 public static void Main (String args[]) {6 Bytearrayoutputstream BAOs = new by Tearrayoutputstream (); 7//When the constructor method is called, a ByteArray byte array 8 dataoutputstream dos = new DataOutputStream (BAOs) is created in memory first; 9//On the outside of the output stream, a layer of data flow is used to process the int,double type of the number of try{11 dos.writedouble (Math.random ());//writes the resulting random number directly to the byte Array ByteArray Dos.writeboolean (TRUE);//Boolean data in memory only takes one byte bytearrayinputstream Bais = new ByteArray InputStream (Baos.tobytearray ()); System.out.println (Bais.available ()); DataInputStream dis = n             EW DataInputStream (Bais), System.out.println (Dis.readdouble ()),///first read it first, call the Readdouble () method to read the random number written 17             System.out.println (Dis.readboolean ());//After the written in the read out, the reading order in this can not change the position, otherwise it will print incorrect results dos.close (); 19 Bais.close ();}catch (Exception e) {e.printstacktrace ();22}23}24} 

by Bais This stream to read the data outside, is a byte to read out of a byte, so that the data read can not be judged to be a string or bool type of value, so to set a stream outside of it, through the DataInputStream to read the data conversion can be judged. Note: When reading the data is written first, read it first, so read ByteArray byte array data should be read the number of double type of 8 bytes, and then read the only one byte of the number of the Boolean type, Because the number of the double type is first written into the array, read it first. This is the so-called first-written to read first. If you read the number of the Boolean type first, it is possible to read a byte in the 8 bytes of a double type.

9.4. Print Flow--print

  

Test code:

 1 package cn.gacl.test; 2 3/* This applet is to reset the printout of the window, 4 * The default in the command line window output print content set to other specified print display window 5 */6 import java.io.*; 7 pub                  LIC class testprintstream{8 public static void Main (String args[]) {9 PrintStream PS = null;10 try{11 FileOutputStream fos = new FileOutputStream ("D:/java/log.txt"); PS = new PrintStream (fo s)///The outside of the output stream is a layer of print stream, used to control the printout of the IF (PS! = null) {system.setout (PS);//The Call SetOut () method here changes the Output window, previously written System.out.print () The Default Output window is the command-line window. 15//But now use System.setout (PS) to change the Print Output window to a file specified by PS, after this setting, print output             Will print output in the specified file 16//Here the PrintOut window is set to the Log.txt file, so the printed content will be log.txt in this file to see 17}18                 for (char c=0;c<=60000;c++) {System.out.print (c+ "\ t");//print the words from all over the world to log.txt this file 20 }21}catch (Exception e) {e.printstacktrace ();}24}25} 

9.5. Object Flow--object

  

Test code:

 1 package cn.gacl.test; 2 3 Import java.io.*; 4 5 public class Testobjectio {6 public static void Main (String args[]) {7 T t = new T (); 8 T.K = 8 ;//Change the value of K to 8 9 try {fileoutputstream fos = new FileOutputStream (one "d:/java/tes TObjectIo.txt "); ObjectOutputStream oos = new ObjectOutputStream (FOS);//ObjectOutputStream Flow Special             The door is used to handle the object, the outside of the FOS flow of the socket ObjectOutputStream stream can be directly put an object into the Oos.writeobject (t);//directly write a T object into the specified file 15                     Oos.flush (); Oos.close (); FileInputStream fis = new FileInputStream (18 "D:/java/testobjectio.txt"); ObjectInputStream ois = new ObjectInputStream (FIS);//Object InputStream is specifically used to read an object of T TRead = (t) ois.readobject (); 22//directly read all the contents of the file and break it into an object, and    Use cast to the specified type T23 System.out.print (tread.i + "\ T" + TREAD.J + "\ T" + Tread.d + "\ T" 24                 + TREAD.K); Ois.close (), and the catch (Exception e) {e.printstacktrace ( ); 28}29}30}31 32/*33 * If you want to serialize a class object into a byte stream, you must implement the serializable interface. There is no method defined in the serializable interface, and the Serializable interface is a A labeled interface that is used to mark a class, but only serves as a marker. 35 * This tag is for the compiler to see, after the compiler sees this tag can know that the class can be serialized if you want to serialize the object of a class, you have to implement the Serializable interface */37 class T implements Serializable {3 8//Serializable means can be serialized in the series int i = 10;40 int j = 9;41 Double d = 2.3;42 int k = 15;43//trans ient int k = 15;44//If you add the transient keyword when declaring a variable, the variable is treated as transparent, that is, it does not exist. 45}

The class that implements the serializable interface directly is that the JDK automatically serializes the object of this class, and if the class that implements public interface Externalizable extends serializable can control the serialization of the object itself, It is recommended that you allow the JDK to control the serialization itself without having to control it.

X. Overview of IO Flow

  

IO stream in Java

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.