Java - The Way to Advancement _java Foundation _IO

As a beginner of java, I have been unable to understand the io relationship in java. I have found many of them on the internet, mostly for a sketch description of the structure, but I don't understand them very well. And it does not incorporate the latest technology of Java 7, so I'll sort it out by myself. If you have any mistakes, please correct them, and I hope you can put forward valuable suggestions.

First of all, look at a picture: (If you are a beginner, I believe it's not good for you to see the real person. Think about how hard the java designers are working!)

 

This is the basic processing flow of java io. In addition, we will also mention some advanced processing classes based on io, such as console class, Steam Tokenzier, Externalizable interface, Serializable interface and so on.

 

First, the beginning of java io: files

1. We mainly talk about streaming. The essence of streaming is also the processing of files. We will move from files to streaming step by step.

2. File, the class that Java handles files. Java provides a very detailed file processing method. Several examples are given, and the rest can go.

package com.hxw.io;  
import java.io.*;  
   
public class FileExample{  
    public static void main(String[] args) {  
       
        createFile();  
    }  
   
  /** 
   * Examples of file processing
   */  
  public static void createFile() {  
     File f=new File("E:/Computer desktop/jar/files/create.txt");  
        try{  
            f.createNewFile();  //When and only if there is no file with the specified name of this abstract path name, a new empty file is created indivisibly.   
            System.out.println("The partition size"+f.getTotalSpace()/(1024*1024*1024)+"G"); //Returns the name of the file or directory represented by the abstract path name.   
            f.mkdirs();  //Create the directory specified by this abstract path name, including all necessary but non-existent parent directories.   
//f.delete(); // Delete the file or directory represented by this abstract pathname
           System.out.println("file name  "+f.getName());  //Returns the name of the file or directory represented by the abstract path name.   
           System.out.println("File parent directory string "+f.getParent());//Returns the path name string of the abstract path name parent directory; returns null if the path name does not specify the parent directory.   
            
        }catch (Exception e) {  
            e.printStackTrace();  
        }  
  }  
}  

2. Byte stream:

1. Byte streams have input and output streams. Let's first look at the input stream InputStream. Let's first parse an example (FileInputStream).

 

package com.hxw.io;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
public class FileCount {  
   /** 
    * Let's write a small program to check the length of the file. If you ignore try catch block, you'll find that it's only a few lines.  
    */  
   publicstatic void main(String[] args) {  
      //TODO Automatically Generated Method stub
             int count=0;  //Statistical file byte length
      InputStreamstreamReader = null;   //File input stream
      try{  
          streamReader=newFileInputStream(new File("D:/David/Java/java Advanced level/files/tiger.jpg"));  
          /*1.new File()The file address inside can also be written as D: David Java Java Java Advanced Advancement\\ files\ tiger. jpg. The former is used for the latter.
           * FileInputStream has a buffer for conversion, so it must be closed after it is used up, otherwise it may lead to full memory and loss of data.  
          */  
          while(streamReader.read()!=-1) {  //Read the file bytes and increment the pointer to the next byte.
             count++;  
          }  
          System.out.println("---The length is: "+count+" byte");  
      }catch (final IOException e) {  
          //TODO Automatically Generated catch Block
          e.printStackTrace();  
      }finally{  
          try{  
             streamReader.close();  
          }catch (IOException e) {  
             //TODO Automatically Generated catch Block
             e.printStackTrace();  
          }  
      }  
   }  
   
}  


 

Step by step, first of all, the problem with the above program is that I need to use FileInputStream every time I read it. The result I output is "64982 bytes in length". So I did 64982 operations! It is possible to imagine that if the file is very large, such an operation will definitely cause a big problem, so the concept of buffer is introduced. You can change streamReader.read() to streamReader.read(byte[]b). The number of bytes read by this method is equal to the length of the byte array. The data read is stored in the byte array, and the number of bytes read is returned. InputStream has other methods such as mark, reset and mark Supported, such as:

 

markSupported judges that the input stream supports mark and reset methods.

Mark is used to mark the current position; after reading a certain amount of data (less than readlimit data), reset can be used to return to the mark mark mark position.

FileInputStream does not support mark/reset operation; Buffered InputStream supports this operation;

The meaning of mark(readlimit) is to mark the current position to determine the maximum number of bytes that can be re-read. That is to say, if the number of bytes you read after the mark is greater than the readlimit, you will never be able to return to the location.

Usually when InputStream's read() returns to - 1, it indicates that it reaches the end of the file and cannot be read again. Unless mark/reset is used.

 

 

2.FileOutputStream Progressive Edition, InputStream is the parent of all byte output streams, and its subclasses are ByteArray OutputStream, FileOutputStream, ObjectOutputStreanm, which we will talk about later. First FileOutput Stream

Let me show you the use of caches by way of a file copying program. By default, Java I/O does not buffer streams. The so-called "buffer" is to temporarily store a sequence of bytes from the stream in an internal byte array called buffer, and then you can get the whole block of byte data at once. A stream without buffer can only read byte by byte, which is more efficient or less obvious at a glance. There are two special input streams that implement buffering. One is our commonly used Buffered Input Stream.

package com.hxw.io;  
import java.io.*;  
   
public class FileCopy {  
   
  public static void main(String[] args) {  
     //Method stubs generated automatically by TODO
     byte[] buffer=new byte[512];   //The number of bytes taken out at a time, the size of the buffer.
     int numberRead=0;  
     FileInputStream input=null;  
     FileOutputStream out =null;  
     try {  
        input=new FileInputStream("D:/David/Java/java Advanced level/files/tiger.jpg");  
        out=new FileOutputStream("D:/David/Java/java Advanced level/files/tiger2.jpg"); //If the file does not exist, it will be created automatically.
         
        while ((numberRead=input.read(buffer))!=-1) {  //numberRead is designed to prevent the last read byte from being less than the buffer length.
           out.write(buffer, 0, numberRead);       //Otherwise, it will be automatically filled with 0.
        }  
     } catch (final IOException e) {  
        //TODO automatically generated catch blocks
        e.printStackTrace();  
     }finally{  
        try {  
           input.close();  
           out.close();  
        } catch (IOException e) {  
           //TODO automatically generated catch blocks
           e.printStackTrace();  
        }  
         
     }  
  }  
   
}  

 

3. Read-write objects: ObjectInputStream and ObjectOutputStream, which allow reading or writing user-defined classes, but in order to achieve this function, the read and write classes must implement Serializable interface. In fact, there is no way to implement this interface, which may be equivalent to a tag, but it is not missing. The example code is as follows:

 

package com.hxw.io;  
   
import java.io.*;  
   
public class ObjetStream {  
   
   /** 
    * @param args 
    */  
   public static void main(String[] args) {  
      //Method stubs generated automatically by TODO
      ObjectOutputStream objectwriter=null;  
      ObjectInputStream objectreader=null;  
       
      try {  
         objectwriter=new ObjectOutputStream(new FileOutputStream("D:/David/Java/java Advanced level/files/student.txt"));  
         objectwriter.writeObject(new Student("gg", 22));  
         objectwriter.writeObject(new Student("tt", 18));  
         objectwriter.writeObject(new Student("rr", 17));  
         objectreader=new ObjectInputStream(new FileInputStream("D:/David/Java/java Advanced level/files/student.txt"));  
         for (int i = 0; i < 3; i++) {  
            System.out.println(objectreader.readObject());  
         }  
      } catch (IOException | ClassNotFoundException e) {  
         //TODO automatically generated catch blocks
         e.printStackTrace();  
      }finally{  
         try {  
            objectreader.close();  
            objectwriter.close();  
         } catch (IOException e) {  
            //TODO automatically generated catch blocks
            e.printStackTrace();  
         }  
          
      }  
       
   }  
   
}  
class Student implements Serializable{  
   private String name;  
   private int age;  
    
   public Student(String name, int age) {  
      super();  
      this.name = name;  
      this.age = age;  
   }  
   
   @Override  
   public String toString() {  
      return "Student [name=" + name + ", age=" + age + "]";  
   }  
    
    
}  


 

System output after operation:

Student [name=gg, age=22]

Student [name=tt, age=18]

Student [name=rr, age=17]

4. Sometimes it is not necessary to store the information of the whole Object, but only the member data of an Object. The type of member data is assumed to be the basic data type of Java. This requirement does not need to use flow objects related to Object input and output. Data InputStream and Data OutputStream can be used to write or read data. Here's an example: (The advantage of DataInputStream is that when you read data from a file, you don't have to bother to decide when to stop reading strings or int s, and you can read the complete type data correctly using the corresponding readUTF() and readInt() methods.)

 

package com.hxw;  
public class Member {  
    private String name;  
    private int age;  
    public Member() {  
    }  
   public Member(String name, int age) {  
        this.name = name;  
        this.age = age;  
    }  
    public void setName(String name){  
        this.name = name;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public String getName() {  
        return name;  
    }  
    public int getAge() {  
        return age;  
    }  
}  


 

It is intended to write the member data of an instance of the Member class into a file, and to restore the data to a Member object after reading in the file data. The following code simply demonstrates how to implement this requirement.

 

package com.hxw;  
import java.io.*;  
public class DataStreamDemo  
{  
  public static void main(String[]args)  
  {  
     Member[] members = {newMember("Justin",90),  
                        newMember("momor",95),  
                        newMember("Bush",88)};  
        try  
     {  
        DataOutputStreamdataOutputStream = new DataOutputStream(new FileOutputStream(args[0]));  
   
        for(Member member:members)  
        {  
            //Write UTF string
           dataOutputStream.writeUTF(member.getName());  
           //Writing int data  
           dataOutputStream.writeInt(member.getAge());  
        }  
   
        //All data to destination
        dataOutputStream.flush();  
        //Close the flow.
        dataOutputStream.close();  
   
            DataInputStreamdataInputStream = new DataInputStream(new FileInputStream(args[0]));  
   
        //Read the data and restore it to the object.
        for(inti=0;i<members.length;i++)  
        {  
           //Read out UTF strings
           String name =dataInputStream.readUTF();  
           //Read the int data.
           int score =dataInputStream.readInt();  
           members[i] = newMember(name,score);  
        }  
   
        //Close the flow.
        dataInputStream.close();  
   
        //Display restored data.
        for(Member member : members)  
        {  
           System.out.printf("%s\t%d%n",member.getName(),member.getAge());  
        }  
     }  
     catch(IOException e)  
     {  
            e.printStackTrace();  
     }  
  }  
}  


 

5. The PushbackInputStream class inherits the FilterInputStream class as the modifier of the iputStream class. Provides the ability to insert data into the front end of the input stream (and other operations, of course). In short, the PushbackInputStream class's function is to know what the next byte is in advance when reading the buffer. Its essence is to read the next character and back it. There are many operations that can be done between them. This kind of operation can be done when you read the buffer as an array traversal and traverse a character, of course. If you want to insert, the maximum number of bytes you can insert is related to the size of the push back buffer. The insert character must not be larger than the buffer. Here is an example.

package com.hxw.io;  
   
import java.io.ByteArrayInputStream; //Import the package of ByteArray InputStream
import java.io.IOException;  
import java.io.PushbackInputStream;  
   
/** 
 * Backflow operation
 * */  
public class PushBackInputStreamDemo {  
public static void main(String[] args) throws IOException {  
    String str = "hello,rollenholt";  
    PushbackInputStream push = null; //Declare a backflow object
    ByteArrayInputStream bat = null; //Declare byte array stream objects
    bat = new ByteArrayInputStream(str.getBytes());  
    push = new PushbackInputStream(bat); //Create a backflow object and stream the disassembled byte array into it.
    int temp = 0;  
    while ((temp = push.read()) != -1) { //push.read() byte-by-byte reads are stored in temp and returned - 1 if read is complete.
       if (temp == ',') { //Determine whether the read is a comma?
          push.unread(temp); //Back to temp.
          temp = push.read(); //Then read the bytes.
          System.out.print("(Regression" + (char) temp + ") "); //Output fallback characters
       } else {  
          System.out.print((char) temp); //Otherwise, output characters.
       }  
    }  
}  
}  


 

6.SequenceInputStream: In some cases, when we need to read data into a program from multiple input streams. In this case, a merge stream can be used to merge multiple input streams into a SequenceInputStream stream object. SequenceInputStream combines the connected streams into an input stream and reads from the first input stream until it reaches the end of the file, then reads from the second input stream, and so on, until it reaches the end of the file containing the last input stream. The purpose of merge flow is to merge multiple sources into one source. It can receive multiple byte stream objects enclosed by enumeration classes.

package com.hxw.io;  
   
import java.io.*;  
import java.util.Enumeration;  
import java.util.Vector;  
   
public class SequenceInputStreamTest {  
  /** 
   * @param args 
   *            SequenceInputStream Merge stream, which combines the connected streams into an input stream and reads from the first input stream.
   *            Until the end of the file is reached, then read from the second input stream, and so on until the end of the file containing the last input stream is reached.  
   *            The purpose of merge flow is to merge multiple sources into one source. Receive multiple byte stream objects enclosed by the enumeration class.  
   */  
  public static void main(String[] args) {  
     doSequence();  
  }  
   
  private static void doSequence() {  
     //Create a merge stream object
     SequenceInputStream sis = null;  
     //Create an output stream.   
     BufferedOutputStream bos = null;  
     try {  
        //Build a stream set.   
        Vector<InputStream> vector = new Vector<InputStream>();  
        vector.addElement(new FileInputStream("D:\text1.txt"));  
        vector.addElement(new FileInputStream("D:\text2.txt"));  
        vector.addElement(new FileInputStream("D:\text3.txt"));  
        Enumeration<InputStream> e = vector.elements();  
   
        sis = new SequenceInputStream(e);  
   
        bos = new BufferedOutputStream(new FileOutputStream("D:\text4.txt"));  
        //Reading and writing data
        byte[] buf = new byte[1024];  
        int len = 0;  
        while ((len = sis.read(buf)) != -1) {  
           bos.write(buf, 0, len);  
           bos.flush();  
        }  
     } catch (FileNotFoundException e1) {  
        e1.printStackTrace();  
     } catch (IOException e1) {  
        e1.printStackTrace();  
     } finally {  
        try {  
           if (sis != null)  
              sis.close();  
        } catch (IOException e) {  
           e.printStackTrace();  
        }  
        try {  
           if (bos != null)  
              bos.close();  
        } catch (IOException e) {  
           e.printStackTrace();  
        }  
     }  
  }  
}  


 

7.PrintStream says that the name may not be familiar to beginners. If you say System.out.print(), you must be familiar with it. The object of System.out is PrintStream, which we have not done many examples.

3. Character stream (as the name implies, the stream that operates on character files)

1.java uses Unicode to store strings. When writing to a character stream, we can specify the encoding of the written strings. Previously, we introduced ByteArrayOutputStream, which does not need to throw exceptions to handle byte data. The corresponding classes of operation character classes are CharArrayReader and CharArrayWriter classes. Buffers are also used here, but they are character buffers. Generally speaking, the general method of putting strings into the io stream of operation characters is to use them.

CharArrayReader = mew CharArrayReader (str. toCharArray ()); once you go to the CharArrayReader instance, you can use CharArrayReader to access the elements of the string to perform further reading operations. No examples

2. We use FileReader, PrintWriter to demonstrate.

package com.hxw.io;  
   
import java.io.FileNotFoundException;  
import java.io.FileReader;  
import java.io.IOException;  
import java.io.PrintWriter;  
import java.nio.CharBuffer;  
   
public class Print {  
   
/** 
 * @param args 
 */  
public static void main(String[] args) {  
    //Method stubs generated automatically by TODO
    char[] buffer=new char[512];   //The number of bytes taken out at a time, the size of the buffer.
    int numberRead=0;  
    FileReader reader=null;        //Stream reading character file  
    PrintWriter writer=null;    //The flow of characters to the console
     
    try {  
       reader=new FileReader("D:/David/Java/java Advanced level/files/copy1.txt");  
       writer=new PrintWriter(System.out);  //PrintWriter can output characters to files or consoles.
       while ((numberRead=reader.read(buffer))!=-1) {  
          writer.write(buffer, 0, numberRead);  
       }  
    } catch (IOException e) {  
       //TODO automatically generated catch blocks
       e.printStackTrace();  
    }finally{  
       try {  
          reader.close();  
       } catch (IOException e) {  
          //TODO automatically generated catch blocks
          e.printStackTrace();  
       }  
       writer.close();       //This does not need to throw an exception.
    }  
        
}  
   
}  


 

3. Compared with our previous example, the file opened directly with FileReader, we use link flow this time, which is commonly used. The so-called link flow is the encapsulation of multiple convections, so that we can better manipulate the management data. (For example, we use Data InputStream (FileInputStream) to package the byte stream layer, we can ReadByte () and readChar () are more specific operations. Note that the stream belongs to the byte stream and operates on characters. CharArray Reader is enough for the character stream. The following example uses a variable parameter in j2se 5 for a small extension. BufferedWriter and BufferedReader are used to write in a file cascade, that is, multiple files are written to the same file (BufferedReader and BufferedWriter, the output streams with buffers, which are most commonly used in readLine() method, read a line of data, and return to String).

 

package com.hxw.io;  
   
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.util.Iterator;  
   
public class FileConcatenate {  
   
  /** 
   * Packing classes perform file cascading operations
   */  
  public static void main(String[] args) {  
     //Method stubs generated automatically by TODO
     try {  
        concennateFile(args);  
     } catch (IOException e) {  
        //TODO automatically generated catch blocks
        e.printStackTrace();  
     }  
  }  
  public static voidconcennateFile(String...fileName) throws IOException{  
     String str;  
     //Build your input stream for this file
     BufferedWriter writer=new BufferedWriter(new FileWriter("D:/David/Java/java Advanced level/files/copy2.txt"));  
     for(String name: fileName){  
        BufferedReader reader=new BufferedReader(new FileReader(name));  
         
        while ((str=reader.readLine())!=null) {  
           writer.write(str);  
           writer.newLine();  
        }  
     }  
  }  
   
}  
   

 


 

4.Console class, which provides a method for reading passwords, can prohibit console echo and return char array, two features to ensure security, usually used little, just know.

5.StreamTokenizer class, which is very useful, can parse the input stream into token. StreamTokenizer is not derived from InputStream or OutputStream, but classified into io libraries, because StreamTokenizer only handles InputStream objects.

First of all, I give the content of my text file:

'water drift'

Green grass

"i love wyhss"

{3211}

23223 3523

i love wyh ,.

. ,


 

package com.hxw.io;  
import java.io.BufferedReader;  
import java.io.FileReader;  
import java.io.IOException;  
import java.io.StreamTokenizer;  
   
/** 
 * Use Stream Tokenizer to count the number of characters in a file
 * StreamTokenizer Class takes the input stream and parses it as a tag, allowing one tag to be read at a time.  
 * The analysis process is controlled by a table and many flags that can be set to various states.  
 * The tag generator of the stream can identify identifiers, numbers, referenced strings, and various annotation styles.  
 * 
 *  By default, Stream Tokenizer considers the following as Token: letters, numbers, symbols other than C and C++ annotation symbols.  
 *  If the symbol "/" is not Token, the annotated content is not Token, and "" is Token. Single and double quotation marks and their contents can only be regarded as a Token.  
 *  The procedure of counting the number of characters in an article is not simply to count Token, because the number of characters is not equal to Token. According to Token's regulations,
 *  Even 10 pages of quotation marks are a Token. If you want quotation marks and quotation marks to count as Token, you should call the following code:
 *    st.ordinaryChar('\''); 
 * st.ordinaryChar('\"'); 
 */  
public class StreamTokenizerExample {  
   
    /** 
     * Statistical Character Number
     * @param fileName Filename
     * @return    Character number
     */  
public static void main(String[] args) {  
        String fileName = "D:/David/Java/java Advanced level/files/copy1.txt";  
        StreamTokenizerExample.statis(fileName);  
    }  
    public static long statis(String fileName) {  
   
        FileReader fileReader = null;  
        try {  
            fileReader = new FileReader(fileName);  
            //Create a tag generator that parses a given character stream
            StreamTokenizer st = new StreamTokenizer(new BufferedReader(  
                    fileReader));  
   
            //The ordinaryChar method specifies that character parameters are "normal" characters in this tag generator.   
            //The following specifies that single quotation marks, double quotation marks and comment symbols are common characters.
            st.ordinaryChar('\'');  
            st.ordinaryChar('\"');  
            st.ordinaryChar('/');  
   
            String s;  
            int numberSum = 0;  
            int wordSum = 0;  
            int symbolSum = 0;  
            int total = 0;  
            //The nextToken method reads the next Token.
            //TT_EOF indicates a constant that has been read to the end of the stream.   
            while (st.nextToken() !=StreamTokenizer.TT_EOF) {  
                //After calling the nextToken method, the ttype field will contain the type of tag just read.
                switch (st.ttype) {  
                //TT_EOL indicates a constant that has been read to the end of the line.   
                case StreamTokenizer.TT_EOL:  
                    break;  
                //TT_NUMBER indicates that a constant of a numeric tag has been read.
                case StreamTokenizer.TT_NUMBER:  
                    //If the current tag is a number, the nval field will contain the value of that number.
                    s = String.valueOf((st.nval));  
                    System.out.println("The figures are as follows:"+s);  
                    numberSum ++;  
                    break;  
                //TT_WORD indicates a constant that has read a text tag.
                case StreamTokenizer.TT_WORD:  
                    //If the current tag is a literal tag, the sval field contains a string of characters giving the literal tag.
                    s = st.sval;  
                    System.out.println("The words are: "+s);  
                    wordSum ++;  
                    break;  
                default:  
                    //If none of the above three types is English punctuation marks.
                    s = String.valueOf((char) st.ttype);  
                    System.out.println("Punctuation points are: "+s);  
                    symbolSum ++;  
                }  
            }  
            System.out.println("Number has " + numberSum+"individual");  
            System.out.println("Word has " + wordSum+"individual");  
            System.out.println("The punctuation marks are: " + symbolSum+"individual");  
            total = symbolSum + numberSum +wordSum;  
            System.out.println("Total = " + total);  
            return total;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return -1;  
        } finally {  
            if (fileReader != null) {  
                try {  
                    fileReader.close();  
                } catch (IOException e1) {  
                }  
            }  
        }  
    }  
   
     
}  

The results are as follows:

Punctuation: '

Words are: water rafting

Punctuation: '

The words are: green grass.

Punctuated: "

The words are:i

The words are: love

The words are: wyh

The words are:ss

Punctuated: "

The punctuations are as follows:{

Numbers: 3211.0

Punctuation:}

Numbers: 23223.0

Numbers: 35.23

The words are:i

The words are: love

The words are: wyh

The words are:,.

Numbers are: 0.0

The punctuation is:

There are four figures.

There are 10 words.

There are seven punctuation marks.

Total= 21

 

We can see a lot from it:

1. A single decimal point "." is treated as a number with a value of 0.0;

2. A string of Chinese characters is treated as a word as long as there are no symbols in the middle (blank return semicolons, etc.). Punctuation in Chinese is handled as in Chinese characters.

3. If quotation marks are not converted into ordinary characters, the contents of a quotation mark, no matter how many, are treated as a marker.

4. This class can recognize English punctuation

 

6. There are other sub-interfaces in java IO like Serializable interface, Externalizable interface, which is more complex than Serializable interface. This is not introduced here. There is also something about java object versioning that is interesting to Baidu. The java nio stuff is not covered here, and a subsequent article will be combined with threads to specifically parse this stuff.

Reprinted from: http://davidisok.iteye.com/blog/2106489

Tags: Java less Steam REST

Posted on Thu, 09 May 2019 22:26:38 -0400 by skkeeper