Java learning-IO

Source: Internet
Author: User

Classes or interfaces related to Java stream operations:


Inherited charts in IO


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Signature + signature/Oho7y0yv2 + signature/Signature + CjxsaT64 + signature + uPm + 3cr9vt3B98/Signature + 19a3 + signature + NPQwcu21NfWt/ u9 + NDQuN/Qp7LZ1/hybrid + zcrHu/hybrid + 8H3tcTH + hybrid/vB99LU19a3 + hybrid + 6Os0ru0zr/hybrid + tKbA7bbUz/hybrid + NfWt/hybrid + release/OxLG + yv2 + 3aOsvs3Txc/release + IDwvaDM + release/bB9zwvaDM + release/release + CjxoMj48YnI + CjwvaDI + release/release + release/ release/release + nP88DgoaM8bGk + release/dbWu/release + release/release + 8 nPzbyjrL/J0tS/tLP2o7o8L3A + release/release + nP88DgoaM8bGk + keys/LT68bky/keys + My7X1r3awfe1xMrkyOvT68rks/a1xLbU06Y8L2gzPgo8aW1nIHNyYz0 = "http://www.2cto.com/uploadfile/Collfiles/20140615/20140615094252285.jpg" alt = "\">

In the figure, the blue part is the main corresponding part, and the red part is the non-corresponding part. The purple dotted line indicates that these streams are generally used together. From the figure above, we can see that the byte stream in Java IO is extremely symmetric. "Exist and make sense." Let's look at several classes that are not symmetric in these byte streams!

  1. LineNumberInputStream obtains the corresponding row number when it reads data from the stream. When and where the branch is determined by the change class, there is not such a line number in the original. There is no corresponding part in the output part. We can create a LineNumberOutputStream by ourselves. There will be a baseline line number when we first write data, and a line number will be added to the next line each time we encounter a line change, it looks okay, too. It seems that it is not streaming.
  2. PushbackInputStream is used to view the last byte and put it into the buffer zone if it is not satisfied. It is mainly used in Compiler syntax and lexical analysis. The BufferedOutputStream of the output is almost similar.
  3. The StringBufferInputStream has been Deprecated and should not appear in the InputStream part, mainly because the String should belong to the shard stream range. It has been deprecated. Of course, it is not necessary for the output part! It is also allowed to exist only to keep the version backward compatible.
  4. SequenceInputStream can be considered as a tool class. It reads two or more input streams as one input stream in sequence. It can be removed from the IO package completely without affecting the structure of the IO package, but making it "pure"-pure Decorator mode.
  5. PrintStream can also be considered as an auxiliary tool. Data can be written to other output streams, or FileInputStream. The internal implementation is still buffered. Essentially, it is a tool for the comprehensive use of other streams. I/O packages can be kicked out! System. out and System. out are PrintStream instances! PushbackInputStream usage example

    1. java. io. PushbackInputStream has a PushBack buffer. After reading data from PushbackInputStream, you can use unread () to push data back to the front end as long as the PushBack buffer is not full.

    2. Assume that a text file contains both English characters in the ASCII code range and Chinese characters in the BIG5 range. To determine which locations are ASCII and which are BIG5 Chinese characters, BIG5 Chinese characters use two bytes to represent a Chinese character, while ASCII uses only one byte to represent English characters.

    3. Big5 Chinese characters are ASCII compatible. The low byte range is 0xA4-0xF9, while the high byte is 0x40 -- 0x7E and 0xA1 -- 0xFE. Low bytes are stored first, and then high bytes are stored. Therefore, if you read the byte at 0xA4 -- 0xF9, it indicates that it may be the first half of the data of a Chinese character.

    4. the following example illustrates the PushbackInputStream function. It reads two bytes from the file at a time and checks whether the integer after the two bytes are merged is between 0xA440 -- 0xFFFF, in this way, you can determine whether the two bytes are BIG after merging. If it is BIG5, the two bytes are used to generate a String instance to display Chinese characters. If it is not within this range, it may be characters in the ASCII range, you can display the character representation of the first byte and push back the second byte so that it can be re-read next time.



    Package ysu. hxy; import java. io. *; public class PushbackInputStreamDemo {public static void main (String [] args) {try {PushbackInputStream pushbackInputStream = new PushbackInputStream (new FileInputStream (args [0]); byte [] array = new byte [2]; int tmp = 0; int count = 0; while (count = pushbackInputStream. read (array ))! =-1) {// convert two bytes to an integer tmp = (short) (array [0] <8) | (array [1] & 0xff )); tmp = tmp & 0 xFFFF; // determines whether it is BIG5. if yes, the text in BIG5 is displayed if (tmp> = 0xA440 & tmp <0 xFFFF) {System. out. println ("BIG5:" + new String (array);} else {// push the second byte back to pushbackInputStream. unread (array,); // displays the characters in the ASCII range: System. out. println ("ASCII:" + (char) array [0]) ;}} pushbackInputStream. close ();} catch (ArrayIndexOutOfBoundsException e) {System. out. println ("Please specify the file name");} catch (IOException e) {e. printStackTrace ();}}}

    4. character input stream Reader

    The above inheritance graph shows that:

    1. Reader is the parent class of all input streams. It is an abstract class.
    2. CharReader and StringReader are two basic media streams. They read data from Char arrays and strings respectively. PipedReader reads data from pipelines shared with other threads.
    3. BufferedReader is obviously a decoration device, and its sub-classes are used to decorate other Reader objects.
    4. FilterReader is the parent class of all custom decorative streams. Its subclass PushbackReader is used to decorate the Reader object and adds a row number.
    5. InputStreamReader is a bridge between byte streams and primary streams. It converts byte streams into primary streams. FileReader can be said to be a commonly used tool class to achieve this function. In its source code, the FileInputStream is obviously used as a Reader method. We can get some tips from this class. The usage and usage of each class in Reader are basically the same as that in InputStream. There will be a ing between Reader and InputStream. 5. character output stream Writer

      The preceding graph shows that:

      1. Writer is the parent class of all output streams. It is an abstract class.
      2. CharArrayWriter and StringWriter are two basic media streams that write data to Char arrays and strings respectively. PipedWriter writes data to pipelines shared with other threads,
      3. BufferedWriter is a decorator that provides the buffer function for Writer.
      4. PrintWriter and PrintStream are extremely similar in functionality and usage.
      5. OutputStreamWriter is a bridge between OutputStream and Writer. Its subclass FileWriter is actually a specific class that implements this function (you can study SourceCode ). Functions and usage are very similar to those of OutputStream, and their corresponding graphs will be shown later. 6. ing between input and output of the upstream Stream 7. Conversion Between the upstream stream and the byte stream

        Conversion stream features:

        1. It is a bridge between the traffic flow and the word throttling.
        2. You can convert the byte data to a character through specified encoding.
        3. Character data can be converted to bytes by specified encoding.

          When to use a conversion stream?

          1. When there is a conversion between byte and character;
          2. When the stream operation data needs to be encoded or decoded.

            Specific Object embodiment:

            1. InputStreamReader: a bridge between byte and character
            2. OutputStreamWriter: a bridge between character and byte

              These two stream objects are members of the character system. They have a conversion function, and they are character streams. Therefore, byte stream objects need to be input during construction.

              8. File class

              A File class is an object that encapsulates files and folders in a File system. You can use the object idea to operate files and folders. File class stores various metadata information about a File or directory, including the File name, File length, last modification time, whether the File is readable, and obtaining the path name of the current File, determine whether a specified file exists, obtain the file list in the current directory, and create or delete files and directories.

              9. RandomAccessFile class

              This object is not a member of the stream system. It encapsulates the byte stream and a buffer (character array) to operate data in the character array through internal pointers. Features:

              1. This object can only operate on files. Therefore, the constructor receives two types of parameters: a. String File path and B. File object.
              2. This object can both read and write files. You can specify the operation mode (r, rw) when instantiating objects)

                Note: When the object is instantiated, if the file to be operated does not exist, it will be automatically created. If the file exists and the write data is not specified, it will be written from the beginning, that is, overwrite the original content. It can be used to download data in multiple threads or write data to files simultaneously.

                ========================================================== ========================================================== =============== 1. Stream applications
                import java.io.*;class StreamTest{public static void main(String[] args) throws Exception{/*int data;while((data=System.in.read())!=-1){System.out.write(data);}*//*FileOutputStream fos=new FileOutputStream("1.txt");//fos.write("http://www.mybole.com.cn".getBytes());//fos.close();BufferedOutputStream bos=new BufferedOutputStream(fos);//bos.write("http://www.mybole.com.cn".getBytes());//bos.flush();//bos.close();DataOutputStream dos=new DataOutputStream(bos);byte b=3;int i=78;char ch='a';float f=4.5f;dos.writeByte(b);dos.writeInt(i);dos.writeChar(ch);dos.writeFloat(f);dos.close();FileInputStream fis=new FileInputStream("1.txt");BufferedInputStream bis=new BufferedInputStream(fis);*//*byte[] buf=new byte[100];//int len=fis.read(buf);int len=bis.read(buf);System.out.println(new String(buf,0,len));//fis.close();bis.close();*//*DataInputStream dis=new DataInputStream(bis);System.out.println(dis.readByte());System.out.println(dis.readInt());System.out.println(dis.readChar());System.out.println(dis.readFloat());dis.close();*//*FileOutputStream fos=new FileOutputStream("1.txt");OutputStreamWriter osw=new OutputStreamWriter(fos);BufferedWriter bw=new BufferedWriter(osw);bw.write("http://www.mybole.com.cn");bw.close();FileInputStream fis=new FileInputStream("1.txt");InputStreamReader isr=new InputStreamReader(fis);BufferedReader br=new BufferedReader(isr);System.out.println(br.readLine());br.close();*/InputStreamReader isr=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(isr);String strLine;while((strLine=br.readLine())!=null){System.out.println(strLine);}br.close();}}

                ========================================================== ========================================================== ================================= 2. PipedStream applications
                import java.io.*;class PipedStreamTest{public static void main(String[] args){PipedOutputStream pos=new PipedOutputStream();PipedInputStream pis=new PipedInputStream();try{pos.connect(pis);new Producer(pos).start();new Consumer(pis).start();}catch(Exception e){e.printStackTrace();}}}class Producer extends Thread{private PipedOutputStream pos;public Producer(PipedOutputStream pos){this.pos=pos;}public void run(){try{pos.write("Hello,welcome you!".getBytes());pos.close();}catch(Exception e){e.printStackTrace();}}}class Consumer extends Thread{private PipedInputStream pis;public Consumer(PipedInputStream pis){this.pis=pis;}public void run(){try{byte[] buf=new byte[100];int len=pis.read(buf);System.out.println(new String(buf,0,len));pis.close();}catch(Exception e){e.printStackTrace();}}}

                ========================================================== ========================================================= 3. ObjectSerialStream
                import java.io.*;class ObjectSerialTest{public static void main(String[] args) throws Exception{Employee e1=new Employee("zhangsan",25,3000.50);Employee e2=new Employee("lisi",24,3200.40);Employee e3=new Employee("wangwu",27,3800.55);FileOutputStream fos=new FileOutputStream("employee.txt");ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(e1);oos.writeObject(e2);oos.writeObject(e3);oos.close();FileInputStream fis=new FileInputStream("employee.txt");ObjectInputStream ois=new ObjectInputStream(fis);Employee e;for(int i=0;i<3;i++){e=(Employee)ois.readObject();System.out.println(e.name+":"+e.age+":"+e.salary);}ois.close();}}class Employee implements Serializable{String name;int age;double salary;transient Thread t=new Thread();public Employee(String name,int age,double salary){this.name=name;this.age=age;this.salary=salary;}private void writeObject(java.io.ObjectOutputStream oos) throws IOException{oos.writeInt(age);oos.writeUTF(name);System.out.println("Write Object");}private void readObject(java.io.ObjectInputStream ois) throws IOException{age=ois.readInt();name=ois.readUTF();System.out.println("Read Object");}}

                ========================================================== =============================================================== 4, RandomFIle
                import java.io.*;class RandomFileTest{public static void main(String[] args) throws Exception{Student s1=new Student(1,"zhangsan",98.5);Student s2=new Student(2,"lisi",96.5);Student s3=new Student(3,"wangwu",78.5);RandomAccessFile raf=new RandomAccessFile("student.txt","rw");s1.writeStudent(raf);s2.writeStudent(raf);s3.writeStudent(raf);Student s=new Student();raf.seek(0);for(long i=0;i
                               
                                
                =========================================================================5、File
                import java.io.*;class FileTest{public static void main(String[] args) throws Exception{//File f=new File("1.txt");//f.createNewFile();//f.mkdir();//File f=new File("E:\\JavaLesson\\Lesson7\\1.txt");//f.createNewFile();/*File fDir=new File(File.separator);String strFile="JavaLesson"+File.separator+"Lesson7"+File.separator+"1.txt";File f=new File(fDir,strFile);f.createNewFile();//f.delete();f.deleteOnExit();Thread.sleep(3000);*//*for(int i=0;i<5;i++){File f=File.createTempFile("winsun",".tmp");f.deleteOnExit();}Thread.sleep(3000);*/File fDir=new File(File.separator);String strFile="JavaLesson"+File.separator+"Lesson6";File f=new File(fDir,strFile);String[] names=f.list(new FilenameFilter(){public boolean accept(File dir,String name){return name.indexOf(".java")!=-1;}});for(int i=0;i
                                 
                                  
                =====================================================================================6、
                import java.util.*;import java.nio.charset.*;class CharsetTest{public static void main(String[] args) throws Exception{/*Map m=Charset.availableCharsets();Set names=m.keySet();Iterator it=names.iterator();while(it.hasNext()){System.out.println(it.next());}*/Properties pps=System.getProperties();//pps.list(System.out);pps.put("file.encoding","ISO-8859-1");int data;byte[] buf=new byte[100];int i=0;while((data=System.in.read())!='q'){buf[i]=(byte)data;i++;}String str=new String(buf,0,i);//System.out.println(str);String strGBK=new String(str.getBytes("ISO-8859-1"),"GBK");System.out.println(strGBK);}}



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.