Java IO flow case detailed

Source: Internet
Author: User
Tags uppercase letter
the concept and function of flow

Learning Java IO, you have to mention the Javaio stream.

A stream is a sequence of byte sets with a starting point and an end point, which is the general term or abstraction of the data transfer. That is, the data transfer between the two devices is called flow, the essence of the stream is data transmission, according to the data transmission characteristics of the flow into various classes, easy to more intuitive data operations. Classification of IO streams

According to the different processing data types are divided into: character streams and byte streams

According to the different data flow is divided into: input stream and output stream character streams and byte stream

The origin of character streams: Because of the difference in data encoding, there is a stream object that efficiently operates on characters. The essence is actually based on the byte stream reading, to check the specified code table. The difference between a stream of bytes and a character:

(1) The reading and writing units are different: The byte stream is in bytes (8bit), the character streams are in characters, the characters are mapped according to the Code table, and multiple bytes may be read at a time.

(2) Different processing objects: The byte stream can handle all types of data (such as pictures, AVI, etc.), while character streams can only handle character type data.

(3) The byte stream is not used in the operation of the buffer itself, is the direct operation of the file itself, and the character streams in the operation of the time after the buffer is used, is through the buffer to manipulate the file, we will verify this below.

Conclusion: The choice of byte throttling is preferred. First, because all the files on the hard disk are transmitted or saved in bytes, including pictures and so on. But the character only in memory will be formed, so in the development of the word throttling use a wide range. input and output streams

The input stream can only be read operation, the output stream can only write operations, the program needs to be transmitted according to the different characteristics of the data to use a different flow. a class or interface that is related to a Java stream operation:

Java Streaming class diagram structure:

Java io Stream object 1. Input byte stream inputstream definition and structure description:

You can see from the inheritance graph of the input byte stream:

InputStream is the parent class of all input byte streams, which is an abstract class.

Bytearrayinputstream, StringBufferInputStream, and FileInputStream are three basic media streams that read data from byte arrays, StringBuffer, and local files, respectively. PipedInputStream is a separate description of the knowledge associated with piped, which reads data from pipelines that are shared with other threads.

ObjectInputStream and all filterinputstream subclasses are decorated streams (the protagonist of the adorner pattern). This means that the FileInputStream class can create an object, FileInputStream (string name), with a string path name. And DataInputStream must decorate a class to return an object, DataInputStream (InputStream in). The following illustration:



Instance Operation Demo:

Case reads the contents of the file

/** *
 bytes Stream
 * Read file content
 *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       InputStream in=new FileInputStream (f);
       Byte[] B=new byte[1024];
       In.read (b);
       In.close ();
       System.out.println (New String (b));
    }

Note: In this example, because the length of the B-byte array is 1024, if the file is small, there will be a large number of padding spaces. We can use the return value of In.read (b) to design the program, the following case:

Case reads the contents of the file

/** *
 bytes Stream
 * Read file content
 *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       InputStream in=new FileInputStream (f);
       Byte[] B=new byte[1024];
       int Len=in.read (b);
       In.close ();
       System.out.println ("read into length:" +len);
       System.out.println (New String (B,0,len));
    }

Note: Looking at the above example, we can see that we've applied for a space of a specified size, but sometimes the space may be too small, sometimes too big, we need the exact size to save space, so we can do this:

Case reads the contents of the file

/** *
 byte stream
 * Read the file content, save space
 * * * *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       InputStream in=new FileInputStream (f);
       Byte[] b=new byte[(int) f.length ()];
       In.read (b);
       System.out.println ("File length is:" +f.length ());
       In.close ();
       System.out.println (New String (b));
    }
"Case" read-by-byte

/** *
 byte stream
 * Read the file content, save space
 * * * *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       InputStream in=new FileInputStream (f);
       Byte[] b=new byte[(int) f.length ()];
       for (int i = 0; i < b.length i++) {
           b[i]= (byte) in.read ();
       }
       In.close ();
       System.out.println (New String (b));
    }

Note: The above examples are all about how large the contents of the file, and then unfold, sometimes we do not know how large the file, in this case, we need to determine whether the end of the original file.

"Case" byte stream read file

/** *
 bytes Stream
 * Read File
 *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       InputStream in=new FileInputStream (f);
       Byte[] B=new byte[1024];
       int count =0;
       int temp=0;
       while ((Temp=in.read ())!= ( -1)) {
           b[count++]= (byte) temp;
       }
       In.close ();
       System.out.println (New String (b));
    }

Note: When you read the end of the file, you return-1. Normally, it will not return-1.

"Case" DataInputStream class

Import Java.io.DataInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
  
public class dataoutputstreamdemo{public
   static void Main (string[] args) throws ioexception{
       File File = new file ("D:" + File.separator + "Hello.txt");
       DataInputStream input = new DataInputStream (new FileInputStream (file));
       char[] ch = new CHAR[10];
       int count = 0;
       char temp;
       while (temp = Input.readchar ())!= ' C ') {
           ch[count++] = temp;
       }
       SYSTEM.OUT.PRINTLN (CH);
    }
}
"Case" Pushbackinputstream fallback operation

Import Java.io.ByteArrayInputStream;
Import java.io.IOException;
Import Java.io.PushbackInputStream;
  
/**
 * Back flow operation
 */Public
class pushbackinputstreamdemo{public
    static void Main (string[) args) throwsioexception{
       String str = "Hello,rollenholt";
       Pushbackinputstream push = null;
       Bytearrayinputstream bat = null;
       BAT = new Bytearrayinputstream (Str.getbytes ());
       push = new Pushbackinputstream (BAT);
       int temp = 0;
       while (temp = Push.read ())!=-1) {
           if (temp = = ', ') {
                push.unread (temp);
                temp = Push.read ();
                System.out.print ("(Fallback" + (char) temp + ")");
           } else{
                System.out.print ((char) temp);}}}
2. Output byte stream outputstream Definition and Structure description:

The image of the output byte stream in IO is shown above, as you can see:

OutputStream is the parent class of all output byte streams, which is an abstract class.

Bytearrayoutputstream, FileOutputStream are two basic media streams that write data to byte arrays, and local files, respectively. PipedOutputStream writes data to a pipe that is shared with other threads.

ObjectOutputStream and all filteroutputstream subclasses are decorated streams. The specific example is corresponding to the InputStream. Instance Operation Demo:

Case writes a string to a file

/** *
 Byte stream *
 writes a string to the file
 * *
/import
java.io.*; Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       OutputStream out =new FileOutputStream (f);
       String str= "Hello World";
       Byte[] B=str.getbytes ();
       Out.write (b);
       Out.close ();
    }

You can also write files one byte at a byte:

"Case" writes bytes to file

/**
 * Byte stream
 * Write string to a byte in the file
 * *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       OutputStream out =new FileOutputStream (f);
       String str= "Hello world." ";
       Byte[] B=str.getbytes ();
       for (int i = 0; i < b.length i++) {
           out.write (b[i]);
       Out.close ();
    }
Cases append new content to file

/**
 * Byte stream
 * Append new content to file:
 * * *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       String filename= "D: +file.separator+" Hello.txt ";
       File F=new file (fileName);
       OutputStream out =new FileOutputStream (f,true);//true indicates append mode, otherwise overwrite
       String str= "Rollen";
       String str= "\r\nrollen"; Can be changed line
       byte[] b=str.getbytes ();
       for (int i = 0; i < b.length i++) {
           out.write (b[i]);
       Out.close ();
    }
"Case" Copy file

copy of/** * * * * * *
/import java.io.*;
Class hello{public
   static void Main (string[] args) throws IOException {
       if (args.length!=2) {
           SYSTEM.OUT.PRINTLN ("The command line parameter input is incorrect, please check");
           System.exit (1);
       }
       File File1=new file (Args[0]);
       File File2=new file (args[1]);
         
       if (!file1.exists ()) {
           System.out.println ("The copied file does not exist");
           System.exit (1);
       }
       InputStream input=new FileInputStream (file1);
       OutputStream output=new FileOutputStream (file2);
       if ((input!=null) && (output!=null)) {
           int temp=0;
           while ((Temp=input.read ())!= ( -1)) {
                output.write (temp);
           }
       }
       Input.close ();
       Output.close ();
    }
"Case" converts an uppercase letter to a lowercase letter using the memory action flow

/**
 * Converts an uppercase letter to a lowercase letter
 *
/import java.io.* using the memory operation stream;
Class hello{public
   static void Main (string[] args) throws IOException {
       String str= "Rollenholt";
       Bytearrayinputstream input=new Bytearrayinputstream (Str.getbytes ());
       Bytearrayoutputstream output=new Bytearrayoutputstream ();
       int temp=0;
       while ((Temp=input.read ())!=-1) {
           char ch= (char) temp;
           Output.write (Character.tolowercase (CH));
       String outstr=output.tostring ();
       Input.close ();
       Output.close ();
       System.out.println (OUTSTR);
    }
Case validation Pipeline flow: interprocess communication

/** * Verify Pipeline Flow * * */import java.io.*;
   /** * Message Send class * * */class Send implements runnable{private PipedOutputStream out=null;
    Public Send () {out=new pipedoutputstream ();
    Public PipedOutputStream Getout () {return this.out;
       public void Run () {String message= "Hello, Rollen";
       try{Out.write (Message.getbytes ());
       }catch (Exception e) {e.printstacktrace ();
       }try{Out.close ();
       }catch (Exception e) {e.printstacktrace ();
   /** * Accept Message Class * * */class Recive implements runnable{private PipedInputStream input=null;
    Public Recive () {this.input=new pipedinputstream ();
    Public PipedInputStream GetInput () {return this.input;
       public void Run () {byte[] b=new byte[1000];
       int len=0;
       try{Len=this.input.read (b);
       }catch (Exception e) {e.printstacktrace (); }try{input.cLose ();
       }catch (Exception e) {e.printstacktrace ();
    } System.out.println ("Accepted content is" + (new String (B,0,len)); }/** * Test class * * */class hello{public static void Main (string[] args) throws IOException {send send=new send
       ();
        Recive recive=new Recive ();
       try{//Pipe connection Send.getout (). Connect (Recive.getinput ());
       }catch (Exception e) {e.printstacktrace ();
       New Thread (send). Start ();
    New Thread (recive). Start (); }
}
Case DataOutputStream Class Example

Import Java.io.DataOutputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
public class dataoutputstreamdemo{public
   static void Main (string[] args) throws ioexception{
       File File = new file ("D:" + File.separator + "Hello.txt");
       char[] ch = {' A ', ' B ', ' C '};
       DataOutputStream out = null;
       out = new DataOutputStream (new FileOutputStream (file));
       for (char temp:ch) {
           Out.writechar (temp);
       }
       Out.close ();
    }

"Case" Zipoutputstream class

Let's take a look at the inheritance relationship of the Zipoutputstream class

Java.lang.Object

Java.io.OutputStream

Java.io.FilterOutputStream

Java.util.zip.DeflaterOutputStream

Java.util.zip.ZipOutputStream

Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipOutputStream;
  
public class zipoutputstreamdemo1{public
   static void Main (string[] args) throws ioexception{
       File File = new file ("D:" + File.separator + "Hello.txt");
       File ZipFile = new file ("D:" + File.separator + "Hello.zip");
       InputStream input = new FileInputStream (file);
       Zipoutputstream zipout = new Zipoutputstream (new FileOutputStream (
                zipfile));
       Zipout.putnextentry (New ZipEntry (File.getname ()));
       Set
       the annotation zipout.setcomment ("Hello");
       int temp = 0;
       while (temp = Input.read ())!=-1) {
           zipout.write (temp);
       }
       Input.close ();
       Zipout.close ();
    }
"Case" Zipoutputstream class compresses multiple files

Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.util.zip.ZipEntry;
  
Import Java.util.zip.ZipOutputStream;
       /** * Compress multiple files at once */public class zipoutputstreamdemo2{public static void Main (string[] args) throws ioexception{
       The folder to be compressed file = new File ("D:" + file.separator + "temp");
       File ZipFile = new file ("D:" + File.separator + "Zipfile.zip");
       InputStream input = null;
       Zipoutputstream zipout = new Zipoutputstream (new FileOutputStream (ZipFile));
       Zipout.setcomment ("Hello");
           if (File.isdirectory ()) {file[] files = file.listfiles ();
                for (int i = 0; i < files.length ++i) {input = Newfileinputstream (Files[i]);
               Zipout.putnextentry (Newzipentry (file.getname () + File.separator +files[i].getname ()));
         int temp = 0;       while (temp = Input.read ())!=-1) {zipout.write (temp);
           } input.close ();
    } zipout.close (); }
}
"Case" ZipFile class show

Import Java.io.File;
Import java.io.IOException;
Import Java.util.zip.ZipFile;
  
/**
 *zipfile Demo
 * *
/public class zipfiledemo{public
   static void Main (string[) args) throws {
       File File = new file ("D:" + File.separator + "Hello.zip");
       ZipFile zipfile = new ZipFile (file);
       System.out.println ("The name of the compressed file is:" + zipfile.getname ());
    }
Case uncompressed file (only one file in a compressed file)

Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipFile;
  
/**
 * Extract files (only one file in a compressed file) */public
class zipfiledemo2{public
   static void Main (string[) args) Throws ioexception{
       file = new file ("D:" + File.separator + "Hello.zip");
       File outfile = new file ("D:" + File.separator + "UnZipFile.txt");
       ZipFile zipfile = new ZipFile (file);
       ZipEntry entry =zipfile.getentry ("Hello.txt");
       InputStream input = Zipfile.getinputstream (entry);
       OutputStream output = new FileOutputStream (outfile);
       int temp = 0;
       while (temp = Input.read ())!=-1) {
           output.write (temp);
       }
       Input.close ();
       Output.close ();
    }
Case Zipinputstream class to extract a compressed file containing multiple files

Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipFile;
  
Import Java.util.zip.ZipInputStream;
        /** * Unzip a compressed file containing multiple files */public class zipfiledemo3{public static void Main (string[] args) throws ioexception{
       File File = new file ("D:" +file.separator + "Zipfile.zip");
       File outfile = null;
       ZipFile zipfile = new ZipFile (file);
       Zipinputstream zipinput = new Zipinputstream (new FileInputStream (file));
        ZipEntry entry = null;
       InputStream input = null;
       OutputStream output = null;
           while ((entry = Zipinput.getnextentry ())!= null) {System.out.println ("unzip" + entry.getname () + "file");
           outfile = new File ("D:" + File.separator + entry.getname ()); if (!outfile.getparentfile (). exists ()) {Outfile.getparentfile (). mkdir ();
           } if (!outfile.exists ()) {outfile.createnewfile ();
           Input = Zipfile.getinputstream (entry);
           Output = new FileOutputStream (outfile);
           int temp = 0;
           while (temp = Input.read ())!=-1) {output.write (temp);
           } input.close ();
       Output.close (); }
    }
}
3. The input and output of the byte stream corresponds to the diagram

The blue in the figure is the main counterpart, and the red part is not the corresponding part. The purple dotted line is typically used to match these flows. You can see from the above diagram that the byte stream in the Java IO is extremely symmetric. Philosophically speaking, "existence and rationality", let's take a look at some of the less symmetrical classes in the stream of words. 4. Several special input flow class analysis Linenumberinputstream

The main completion of reading data from the stream, you will get the corresponding line number, as to when the branch, where the branch is determined by the modified class, not in the original has such a line number. In the output section there is no corresponding section, we can create a linenumberoutputstream, the initial write will have a baseline line number, each time you encounter a newline will add a line number on the next line, it seems to be possible. It seems to be a less inflow. Pushbackinputstream

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.