Java Basic IO Framework

Source: Internet
Author: User

First, the concept of flow

the concept of stream is derived from the concept of piping (pipe) in Unix. In Unix, a pipeline is an uninterrupted stream of bytes used to communicate between programs or processes, or to read and write peripherals, external files, and so on.
A stream, which must have both the source and destination, can be some area of computer memory, a disk file, or even a URL on the Internet.
The direction of the flow is important, depending on the direction of the flow, the flow can be divided into two categories: the input stream and the output stream. The user can read the information from the input stream, but cannot write it. Instead, the output stream can only be written to the input stream, not read it.
In fact, the source and destination of a stream can simply be seen as a producer and consumer of bytes, and for an input stream, you don't have to care what its source is, simply read the data from the stream, and on the output stream, you don't know its destination, just simply write the data to the stream. Image metaphor--water flow, file ====== program, file and program connect a pipe, the water flow is formed between, naturally there is a direction: can flow into, can also outflow. Easy to understand, so define the flow: a flow is a pipe with running water, this pipe connects files and programs.
Ii. Classification of Streams
    1. The classes in the Java.io package correspond to two types of flows, which are read or written directly from a specified location (such as a disk file or memory region), which is called a node stream, and the other flows are called filters (filters). The filter input stream is often used as its input source for other input streams, filtered or processed and then provided to the user in the form of a new input stream, and the filter output stream is similar in principle.
    2. Common input and output streams for Java
the Stream class in the Java.io package can be divided into two main categories depending on whether the type of object they manipulate is character or byte: character stream and stream of bytes.
  • BYTE stream in Java
InputStream is the ancestor of all byte input streams, and OutputStream is the ancestor of all byte output streams.
  • Character Stream of Java
Reader is the ancestor of all read string input streams, while writer is the ancestor of all output strings. In combination with the start of the input/output stream, there is a small frame.

Java byte stream

    • FileInputStream and FileOutputStream
      These two classes belong to the node stream, the source side of the first class and the destination end of the second class are disk files, and their construction methods allow the corresponding stream to be constructed through the file's path name. Such as:
      FileInputStream infile = new FileInputStream ("Myfile.dat");
      FileOutputStream outfile = new FileOutputStream ("Results.dat");

It is important to note that, when constructing the FileInputStream, the corresponding file must be present and readable, and when the FileOutputStream is constructed, such as the output file already exists, it must be overwritten.

    • Bufferedinputstream and Bufferedoutputstream
      They are filter flows, and their effect is to improve the efficiency of the input and output.
    • DataInputStream and DataOutputStream
      The objects created by these two classes are called data input streams and data output streams, respectively. This is a useful two stream that allows programs to read and write Java data in a machine-independent style. Therefore, it is more suitable for data transmission on the network. These two streams are also filter flows, often with other flows such as InputStream or outputstream as their inputs or outputs.
Character Stream of Java
Character streams are primarily used to handle characters. Java uses 16-bit Unicode to represent strings and characters, and the corresponding character streams are called readers and writers by input and output respectively.
    • InputStreamReader and OutputStreamWriter
      When constructing the corresponding streams for these two classes, they are automatically converted to convert the platform's default encoding set of encoded bytes to Unicode characters. For the English environment, its default encoding set is generally iso8859-1.
    • BufferedReader and BufferedWriter
      These two classes correspond to a stream that uses buffering, which can greatly improve the efficiency of the input and output. These two are also filter flows, which are often used to process inputstreamreader and OutputStreamWriter. Such as:
1 Import java.io.*; 2 public class Echo {3 public   static void Main (string[] args) {4     BufferedReader in = 5       new BufferedReader (6         new InputStreamReader (system.in)); 7     String s; 8     try {9 while       (s = in.readline ()). Length ()! = 0)         System.out.println (s);       Empty line terminates the Program12     } catch (IOException e) {       e.printstacktrace ();     }15   
The program accepts keyboard input and echoes back.

For the BufferedReader class, The ReadLine () method of the class can read one line from the stream at a time, but for the BufferedWriter class, there is no way to write one line at a time, so to write one line at a time to the stream, The PrintWriter class can be used to change the original stream into a new print stream, and the PrintWriter class has a method println () to output one line at a time. Such as:

............ PrintWriter out = new PrintWriter (New BufferedWriter (      new FileWriter ("D:\javacode\test.txt")); Out.println (" Hello world! "); o Ut.close ();.. .....

Example:

1, related to the console. Read-in/write-out. A copy of the string is implemented.

1 Import java.io.*; 2 public class textread{3  4 public static void main (string[] args) {5    bufferedreader bf = Null;/*bufferedreader equivalent In a big bucket, is actually the memory, here realizes a lot of read and write, rather than read a byte or character directly write like hard disk, strengthen the protection of the hard disk. *    /6 try{7 while     (true) {//while (true) {} loop Guarantee program does not end 8      9        bf = new BufferedReader (New InputStreamReader ( system.in));        /*system.in is a standard input, System.out is a standard output */11        /*inputstreamreader term that streams bytes into a stream of characters, which is the process of streaming         Here quite with 2 pipes are connected between the system.in and the program.         the *readline () method is more useful, and it also enables better functionality by processing streams.         **/15      String line = Bf.readline (), System.out.println (line      ), and    }catch ( Exception e) {     e.printstacktrace ()    }finally{21     //Be sure to close the stream after use. It is best to put it inside the filally.     try{      if (bf!=null) {       bf.close ();      }28     }catch (Exception e) {        E.printstacktrace ();     32}  }33}

2, file-related read and write. File replication is implemented.

1 Import java.io.*; 2 public class textread{3  4 public static void main (string[] args) {5    File fin,fout;   6    BufferedReader bf = null, 7    printwriter pw = null, 8    try{9     fin = new File ("Zzc.txt");//Note that files and programs must be in the same file Clamp down. Zzc.txt is the file to be copied.     fout = new File ("Copyzzc.txt");//If it is not created automatically. Each     bf = new BufferedReader (new FileReader (Fin)),     pw = new PrintWriter (fout),//printwriter as the print stream, You can also use bufferedwriter.13     String line = Bf.readline (), and     (line!=null) {     pw.println (line); 16 Line      = Bf.readline ();    }catch (Exception e) {     e.printstacktrace ();    }finally{21     try{22     //close file.      if (bf!=null) {       bf.close ();       bf = null;26      }27      if (pw!=null) {       pw.close (); 29       pw = null;30      }     }catch (Exception e) {      e.printstacktrace ();     }34    }35}36}

There are many other classes:

Like the Randomaccessfile class, the serialization interface is very important.

Java has a special type of IO data stream--dataoutputstream--It guarantees that "no matter what machine the data comes from, just use a datainputstream to collect the data, and you can save them in the correct format natively."

Java Basic IO Framework

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.