Illustrate stream stream concept in Java _java

Source: Internet
Author: User
Tags current time object serialization serialization static class

1. Basic input stream and output stream
Flow is one of the most important basic concepts in Java. File read and write, network transceiver, process communication, almost all need to input the output of the place to use the stream.

What is a stream for? is to do the input and output. Why does the input and output need to be "streaming" this way? Because the basic unit of the program's input and output is byte, the input is to get a string of bytes, and the output is to send a string of bytes. But in many cases, it is not possible for a program to receive all the bytes before processing it, but to receive a bit of processing. For example, you download World of Warcraft, it is not possible to download all the memory and then save to the hard disk, but download a bit to save a bit. At this point, the flow of this way is very suitable.

In Java, each stream is an object. The flow is divided into two types: input stream (InputStream) and output stream (OutputStream). For the input stream, you just keep the byte out of the stream, and for the output stream, you just pass the prepared byte string to it.

How does the stream object get? Different external systems, the way to get the stream is different. For example, file reading and writing will create Fileinputstream/fileoutputstream objects, and network traffic is obtained through the Socket object to get the input and output stream. In general, if a class has a method such as getInputStream () or Getoutputstream (), it indicates that it is being input and output through a stream object.

InputStream is an input stream, the following is an example of reading a file through InputStream:

Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.io.FileNotFoundException; 
 
Import Java.util.Arrays; /** * Read file through stream/public class Readfiledemo {//Program entry public static void main (string[] args) {String path = 
  "C:/boot.ini"; 
 
  File File = new file (path); 
  Create an input stream InputStream is; 
  try {is = new FileInputStream (file); The catch (FileNotFoundException e) {System.err.println ("file" + path +) does not exist. 
   "); 
  Return  }//Start reading byte[] content = new Byte[0]; Save read the contents of the file byte[] buffer = new byte[10240]; Define cache try {int eachtime = is.read (buffer);//First read. 
   If the return value is-1, there is no content to read. 
    while (Eachtime!=-1) {//the contents of the read are placed in the buffer and are now merged into the content. 
    Content = concatbytearrays (content, buffer, eachtime); Eachtime = is.read (buffer); Continue reading} catch (IOException e) {System.err.println ("failed to read the contents of the file.") 
   "); 
  E.printstacktrace (); finally { 
   try {is.close (); 
  The exception to catch (IOException e) {//here can be ignored}}//output file contents String Contentstr = new string (content); 
 System.out.println (CONTENTSTR); 
  /** * Merge Two byte strings * * @param bytes1 byte string 1 * @param bytes2 byte string 2 * @param sizeOfBytes2 the length to be removed from the Bytes2 * * * @return The result of the merge of the former SizeOfBytes2 bytes in bytes1 and Bytes2/private static byte[] Concatbytearrays (byte[) bytes1, 
  Byte[] bytes2, int sizeOfBytes2) {byte[] result = arrays.copyof (Bytes1, (Bytes1.length + sizeOfBytes2)); 
  System.arraycopy (bytes2, 0, result, bytes1.length, sizeOfBytes2); 
 return result; 
 } 
}

Although it is very verbose, it is indeed the basic usage of inputstream. Note that this is just an example of how to read a byte string from an input stream. In fact, Java provides a simpler way to read text files. will be introduced later.

It is very simple to use outputstream output compared to reading from a stream. Here is an example:

Import Java.io.OutputStream; 
Import Java.io.FileOutputStream; 
Import Java.io.File; 
Import java.io.IOException; 
Import java.util.Date; 
 
/** 
 * Save current date to file 
 /public 
class Savefiledemo {public 
 
 static void Main (string[] args) throws IOException { 
  String path = ' c:/now.txt '; 
 
  File File = new file (path); 
  if (!file.exists () &&!file.createnewfile ()) { 
   System.err.println () cannot create the file. "); 
   return; 
  } 
 
  OutputStream OS = new FileOutputStream (file); Create an output stream (provided that the file exists) 
  Os.write (New Date (). toString (). GetBytes ());  Writes the current time to the file 
  os.close ();          The stream must be closed before the content is written to the file. 
  System.out.println ("file write complete.") "); 
 } 
} 


Java also provides other ways to stream operations, but they are both extended or packaged for InputStream and OutputStream. So these two classes are the basis, and you have to understand their use.

2. Reader and Writer
InputStream and OutputStream are introduced, followed by Reader and Writer. These two classes are actually wrapping InputStream and outputstream. They do not, however, handle bytes (byte) but characters (char). If the contents of a stream are text, it is easier to deal with Reader/writer. Here is an example of reading a text file with reader:

Import Java.io.FileReader; 
Import java.io.IOException; 
Import Java.io.Reader; 
 
/** 
 * Read Text file * * 
/public class Readtextfiledemo { 
 
 //Program entry public 
 static void Main (string[] args) {
   string Path = "C:/boot.ini"; 
  String content = ""; 
 
  try { 
   Reader reader = new FileReader (path); 
   char[] buffer = new char[10240]; 
   int count; 
 
   while (count = reader.read (buffer))!=-1 { 
    content + + new String (buffer, 0, count); 
   } 
  } catch (Ioexcepti On e) { 
   System.err.println ("Failed to read the file.") "); 
   E.printstacktrace (); 
  } 
 
  SYSTEM.OUT.PRINTLN (content); 
 } 
 
 

As for how to use Writer to write text content to the file, here is no example, reader try to write it.

The example above is still not the most common way to read text files. Java provides BufferedReader, which we usually use to read text files. Here is an example:

Import Java.io.BufferedReader; 
Import Java.io.FileReader; 
Import java.io.IOException; 
 
/** 
 * Read text file with BufferedReader 
/public class ReadTextDemo2 {public 
 
 static void Main (string[] args) {
   string Path = "C:/boot.ini"; 
  String content = ""; 
 
  try { 
   BufferedReader reader = new BufferedReader (new FileReader (path)); 
   String Line; 
   while (line = Reader.readline ())!= null) { 
    content + = line + '/n '; 
   } 
  catch (IOException e) { 
   syste M.err.println ("Failed to read the file. "); 
   E.printstacktrace (); 
  } 
 
  SYSTEM.OUT.PRINTLN (content); 
 } 
 

3. Serialization of objects
Object serialization is also an important aspect of streaming applications. Serialization is the conversion of an object into a string of bytes that can be saved or passed to another Java program. ObjectOutputStream and ObjectInputStream are specifically used to serialize and deserialize. The following is a simple example:

Import Java.io.ObjectOutputStream; 
Import Java.io.FileOutputStream; 
Import Java.io.File; 
Import java.io.IOException; 
Import java.io.Serializable; 
Import Java.io.ObjectInputStream; 
Import Java.io.FileInputStream; 
  
Import java.io.EOFException; 
 /** * Objectoutputstream/objectinputstream Sample. 
 * These two classes are used for serialization and deserialization, respectively. */public class Serializationdemo {public static void main (string[] args) throws Exception {String path = "C 
    :/persons.data "; 
    File F = new file (path); 
    if (!f.exists ()) {f.createnewfile (); 
    } writepersons (path); 
  Readpersons (path); //Read the person object private static void Readpersons (String path) throws IOException from the specified file, classnotfoundexception 
  
    {ObjectInputStream ois = new ObjectInputStream (new FileInputStream (path)); 
    Person p; 
        while (true) {try {p = () Ois.readobject (); 
      SYSTEM.OUT.PRINTLN (P); 
      catch (Eofexception e) {break; 
} 
    }  //Save the person object to the specified file private static void Writepersons (String path) throws IOException {person[] pers 
  
    ONS = new person[]{new Person ("John", "N"), New Person ("Dick", 24)}; 
    ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (path)); 
    for [person Person:persons] {oos.writeobject (person); 
  } oos.close (); }///////////////////////////////////////////////////////////private static class person implements Serializa 
  
    ble {private String name; 
  
    private int age; 
      Public person () {} public person (String name, int age) {this.name = name; 
    This.age = age; 
    Public String GetName () {return name; 
    public void SetName (String name) {this.name = name; 
    public int getage () {return age; 
    public void Setage (int age) {this.age = age; @Override Public STring toString () {return "person{" + "name=" "+ name + '/' +", age= "+ Age +"} 
    '; 
 } 
  } 
}

This example does not see the reading and writing of bytes and characters because all two classes are wrapped. The above is just a simple example, serialization to write good words or a lot of attention. To get a better idea of serialization, look at this. This article focuses on the flow-related parts only. In fact, serialization is very small, because serialization reduces flexibility, so you can not use the words are generally not used.

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.