The JAVA IO API USES details

  • 2020-04-01 02:26:22
  • OfStack

I. theoretical preparation
Flow is an abstract concept, which is the abstraction of input and output devices. In Java programs, the input/output operation of data is carried out in a "stream" way. The device can be files, network, memory, etc. Directional flow, as for the input stream or the output stream is a relative concept, general with program (Mr Ma said the machine) for reference, if the flow of data is a program to equipment, we become the output stream, on the other hand we called the input stream, might think flow as a "water pipes" (a lot of information so to speak), nature is the concept of direction.
The flow hides the specific operations inside the I/O device. All InputStream and Reader derived classes have a basic, inherited read() method that reads a single or byte array.
Java is divided into byte streams (end of Stream) and character streams (end of Reader and Write), and then into input streams (InputStream, Reader) and output streams (OutputStream, Write), input and output relative to memory. When reading characters, use character stream, such as text file, XML(I think XML is clearly composed of alphabetic characters, belongs to ASCII file, why not read it with stream?) And so on. Read binary files with byte streams, such as RAR, EXE, etc., not files (pictures) other than text. The flow at the beginning of a Buffered is simply Buffered to make reading and writing more efficient. Character stream cannot be output directly, need to be converted to byte stream to output (this is really just known)!
There are three basic types of nodes in the Java 2 SDK: file, memory, and pipe.
Let's take a look at the classic picture of the IO chapter in zheng li's textbook.
The stream inherited from InputStream/OutputStream is used to input/output data into the program, and the data unit is byte (byte=8bit), as shown in the figure, the dark color is the node stream, and the light color is the processing stream.
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201311/20131114141246.jpg? 20131014141326 ">
Streams inherited from Reader/Writer are used to input/output data into the program, and the data units are all characters (2byte=16bit), as shown in the figure, the dark color is the node stream, and the light color is the processing stream.
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201311/20131114141258.jpg? 20131014141427 ">

2. Usage analysis
General usage principles of Java IO (part from baidu library) :
(1) classification by data source (destination) :
FileInputStream, FileOutputStream, FileReader, FileWriter
Byte [] : ByteArrayInputStream, ByteArrayOutputStream
Is the Char [] : CharArrayReader CharArrayWriter
String: StringBufferInputStream, StringReader, StringWriter
Network data stream: InputStream, OutputStream, Reader, Writer
(2) according to whether the output is formatted:
To format output: PrintStream, PrintWriter
(3) according to whether to buffer points:
To buffer: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter.
(4) by data format:
Binary format (as long as you're not sure it's plain text) : InputStream, OutputStream and all of its subclasses with the end of the Stream
Plain text format (including plain English and Chinese characters or other coding methods); Reader, Writer and all subclasses of Reader, Writer
(5) points by input and output:
Reader, subclass of type InputStream; Output: Writer, subclass of type OutputStream
(6) special needs:
Conversion classes from Stream to Reader,Writer: InputStreamReader, OutputStreamWriter
Object input and output: ObjectInputStream, ObjectOutputStream
Interprocess communication: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter
Merge input: SequenceInputStream
More specific needs: PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader
            (7) the general criteria for deciding which class to use and its construction process are as follows (without considering special needs) :
Consider the most primitive data format: is it text? Input or output? Do you need to convert streams: InputStreamReader, OutputStreamWriter? What is the data source (destination) : the document? Memory? Network? Buffer: bufferedReader (note: readLine() is defined, and there is a more specific input or output method than read or write).

Some examples
Or the winter vacation time to write, review, folding code plug-in can not find, look at it.
1. The System. In


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestSystemIn {
 public static void main(String[] args) {
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);//Have readline
  String s = null;
  try {
   s = br.readLine();
   while(s!=null) {
    if(s.equalsIgnoreCase("exit")) {
     break;
    }
    System.out.println(s.toUpperCase());
    s = br.readLine();
   }
   br.close();
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
}

  2. The buffer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestBuffer {
 public static void main(String[] args) {
  try {
   //Check the date of change to see if the file is new
   BufferedWriter bw = new BufferedWriter(new FileWriter("d:/java.txt"));
   BufferedReader br = new BufferedReader(new FileReader("d:/java.txt"));
   String s = null;
   for(int i=1; i<100; i++) {
    s = String.valueOf(Math.random());
    bw.write(s);
    bw.newLine();//A newline
   }
   //Refreshes the buffer for the flow, br does not have this method
   bw.flush();
   while((s=br.readLine())!=null) {
    System.out.println(s);
   }
   bw.close();
   br.close();
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
}

      3. A FileInputStream

import java.io.*;
public class TestFileInputStream {
 public static void main(String[] args) {
  FileInputStream in = null;
  try {
   in = new FileInputStream("e:/1.txt");
  }catch(FileNotFoundException e) {
   System.out.println(" Can't find the file ");
   System.exit(-1);
  }
  //The following indicates that the file was found
  int tag = 0;
  try {
   long num = 0;
   while((tag = in.read())!=-1) {
    //Read is a stream of bytes. If there are any Chinese characters, the display will be abnormal
    System.out.print((char)tag);
    num++;
   }
   in.close();
   System.out.println();
   System.out.println(" Were read " + num + " character ");
  }catch(IOException e1) {//Both read and close throw IOException
   System.out.println(" File read error ");
   System.exit(-1);
  }
 }
}

        4.FileOutputStream implements the replication function

import java.io.*;

public class TestFileOutputStream {
 public static void main(String[] args) {
  int b = 0;
  FileInputStream in = null;
  FileOutputStream out = null;
  try {
   in = new FileInputStream("d:/java.txt");
   //The following is automatically created if it does not exist
   out = new FileOutputStream("d:/my_java.txt");
   while((b=in.read())!=-1) {
    out.write(b);
   }
   in.close();
   out.close();
  }catch(FileNotFoundException e) {
   System.out.println(" The specified file could not be found ");
   System.exit(-1);
  }catch(IOException e1) {
   System.out.println(" File copy error ");
   System.exit(-1);

  }
  System.out.println(" File copied "); 
 }
}

        5. The ObjectOutputStream and Serializable

import java.io.*;

public class TestObjectIO {
 public static void main(String[] args) throws Exception {
  T t = new T();
  t.k = 8;
  FileOutputStream fos = new FileOutputStream("d:/1.txt");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(t);
  oos.flush();
  oos.close();

  FileInputStream fis = new FileInputStream("d:/1.txt");
  ObjectInputStream ois = new ObjectInputStream(fis);
  T tRead = (T)ois.readObject();
  System.out.println(tRead.i + " " + tRead.j + " " + tRead.k);
 }
}
class T implements Serializable {
 int i = 10;
 int j = 9;
 double d = 2.3;
 int k = 15;
}

  6. Change the encoding mode

import java.io.*;

public class TestTransForm {
 public static void main(String[] args) {
  try {
   OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:/java.txt"));
   osw.write(" hello 123");//You can write strings directly, including Chinese, because the outer stream is the character stream
   System.out.println(" Coding method: " + osw.getEncoding());//ISO8859_1 is a western European language, also known as latin-1. Orientals are not considered. ISO is Unicode
   osw.close();
   osw = new OutputStreamWriter(new FileOutputStream("d:/java.txt",true),"ISO8859_1");//True means append
   osw.write(" This is the append ");
   System.out.println(" Coding method: " + osw.getEncoding());
   osw.close();
  }catch(IOException e) {
   e.printStackTrace();
  }
 }
}
7.Output redirection
[code]
import java.io.*;

public class TestPrintStream {
 public static void main(String[] args) {
  PrintStream ps = null;
  try {
   FileOutputStream fos = new FileOutputStream("d:/java.txt");
   ps = new PrintStream(fos);

  }catch (IOException e) {
   e.printStackTrace();
  }
  if(ps!=null) {
   System.setOut(ps);//Output redirection
  }
  int ln = 0;
  for(char c=0; c<65535; c++) {
   System.out.print(c + " ");
   if(ln++>100) {
    System.out.println();
    ln = 0; 
   }
  }
 }
}

8. DataStream

import java.io.*;
public class TestDataStream {
 public static void main(String[] args) {
 //Allocate an array of bytes in memory, then an & PI; OutputStream, plus a data stream
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(baos);
  try {//Write read
   dos.writeDouble(Math.random());
   dos.writeBoolean(true);
   ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
   System.out.println(bais.available());//A few bytes are available
   DataInputStream dis = new DataInputStream(bais);
   ////Write first read first (queue), the following two outputs can not be swapped, otherwise the first output of a byte in the double
   System.out.println(dis.readDouble());
   System.out.println(dis.readBoolean());
   dos.close();
   dis.close();
  }catch (IOException e) {
   e.printStackTrace(); 
  }
 }
}

Four. Small problem
Why doesn't Writer/Reader inherit from Stream? Characters will eventually be converted to binary. Writer/Readre inherits from OutputStream/InputStream, which is not a better inheritance level, so why make a separate one, and there are subclasses of Stream that can read and write strings. Answer: single duty. That's far-fetched.


Related articles: