Home>

1.Basic input and output streams

Streams are one of the most important basic concepts in java.File reading and writing, network sending and receiving, process communication,Almost everything where input and output are needed,All use streams.

What does a stream do?It is used for input and output.Why use the "stream" method for input and output?Because the basic unit of program input and output is byte,The input is to get a string of bytes,The output is sending a string of bytes.But in many cases,It is impossible for the program to receive all the bytes before processing.Instead, take a bit to deal with.Let ’s say you download World of Warcraft,It is not possible to download all of them into memory and then save them to the hard disk.Instead, download it and save it.In this case, the stream method is very suitable.

In java, each stream is an object.There are two types of streams:input stream (inputstream) and output stream (outputstream). For input streams,You just need to fetch the bytes from the stream;And for the output stream,You just need to pass the prepared byte string to it.

How is the stream object obtained?Different external systems,The way to get the stream is also different.For example, file reading and writing requires creating a fileinputstream/fileoutputstream object, and network communication uses a socket object to obtain input and output streams.Generally speaking,If a class has methods like getinputstream () or getoutputstream (),It shows that it is input and output through the stream object.

inputstream is the input stream,Here is an example of reading a file through an 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;
/**
 * Reading files via streaming
 * /
public class readfiledemo {
 //program entry
 public static void main (string [] args) {
  string path="c:/boot.ini";
  file file=new file (path);
  //create input stream
  inputstream is;
  try {
   is=new fileinputstream (file);
  } catch (filenotfoundexception e) {
   system.err.println ("File" + path + "does not exist.");
   return;
  }
  //start reading
  byte [] content=new byte [0];//save the file content read
  byte [] buffer=new byte [10240];//define the buffer
  try {
   int eachtime=is.read (buffer);//First read.
A return value of -1 means that nothing is readable.
   while (eachtime!=-1) {
    //The read content is placed in buffer, now merge it into content.
    content=concatbytearrays (content, buffer, eachtime);
    eachtime=is.read (buffer);//continue reading
   }
  } catch (ioexception e) {
   system.err.println ("Failed to read file contents.
");
   e.printstacktrace ();
  } finally {
   try {
    is.close ();
   } catch (ioexception e) {
    //The exception here can be ignored
   }
  }
  //output file content
  string contentstr=new string (content);
  system.out.println (contentstr);
 }
 /**
  * Merge two byte strings
  *
  * @param bytes1
  * @param bytes2
  * @param sizeofbytes2 The length to be fetched from bytes2
  *
  * The result of combining the first sizeofbytes2 bytes in @return 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 ’s horribly written,But this is really the basic usage of inputstream.Note that this is just an example,Describes how to read a byte string from an input stream.In fact, java provides an easier way to read text files.Will be introduced later.

Compared to reading from a stream,Using outputstream output is very simple.Below 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 file.
");
   return;
  }
  outputstream os=new fileoutputstream (file);//Create an output stream (provided the file exists)
  os.write (new date (). tostring (). getbytes ());//write the current time to a file
  os.close ();//the stream must be closed,The content is written to the file.
  system.out.println ("File writing is complete.
");
 }
}

java also provides other stream operation methods,But they both extend or wrap inputstream and outputstream.So these two classes are the basis,You must understand their use.

Reader and writer

Introduced inputstream and outputstream, followed by reader and writer. These two classes are actually a wrapper around inputstream and outputstream.But they don't deal with bytes, they deal with characters. If the content of a stream is all text,It would be easier to handle 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 (ioexception e) {
   system.err.println ("Failed to read the file.
");
   e.printstacktrace ();
  }
  system.out.println (content);
 }
}

As for how to write text to a file with a writer,No examples are given here,Kanguan try to write it yourself.

The above example,Still not the most common way to read text files.Java provides a bufferedreader, which we usually use to read text files.Below is an example:

import java.io.bufferedreader;
import java.io.filereader;
import java.io.ioexception;
/**
 * Use bufferedreader to read text files
 * /
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) {
   system.err.println ("Failed to read the file.
");
   e.printstacktrace ();
  }
  system.out.println (content);
 }
}

Object serialization

Object serialization is also an important aspect of streaming applications.Serialization is to convert an object into a string of bytes,Both can be saved,Can also be passed to other java programs.objectoutputstream and objectinputstream are specifically used for serialization and deserialization.Here 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 example.
 * 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 from the specified file
  private static void readpersons (string path) throws ioexception, classnotfoundexception {
    objectinputstream ois=new objectinputstream (new fileinputstream (path));
    person p;
    while (true) {
      try {
        p=(person) ois.readobject ();
        system.out.println (p);
      } catch (eofexception e) {
        break;
      }
    }
  }
  //save the person object in the specified file
  private static void writepersons (string path) throws ioexception {
    person [] persons=new person [] {
        new person ("Zhang San", 23),        new person ("Li Si", 24)
    };
    objectoutputstream oos=new objectoutputstream (new fileoutputstream (path));
    for (person person:persons) {
      oos.writeobject (person);
    }
    oos.close ();
  }
  ///////////////////////////////////////////////////////////////////
  private static class person implements serializable {
    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 +
          "}";
    }
  }
}

In this example, byte and character reading and writing cannot be seen.Because both classes are wrapped.The above is just a simple example,There are still a lot of details about serialization.Want to learn more about serialization,Check it out here.This article only focuses on the parts related to flow.In fact, serialization is rarely used,Because serialization reduces flexibility,So if you do n’t use it, you generally do n’t use it.

  • Previous Understanding pointer variables in C ++
  • Next How js determines if a visit is from a search engine (spider-man) or a direct visit