IO stream
In Java, IO streams are divided into two types: byte streams and character streams. As the name suggests, byte streams are read and written according to bytes, and characters are accessed according to characters; commonly used file reading is character stream, and byte streams are used in network communication.
The following figure is the overall framework of IO streams in Java:
Byte Stream
In Java, byte streams generally end with streams. The input byte stream is called InputStream, and the output byte stream is called OutputStream; InputStream and OutputStream are superclasses representing all classes of their input/output, and are abstract classes (abstract)
Commonly used byte streams are:
1.FileInputStream/FileOutputStream2.BufferedInputStream/BufferedOutputStream3.SequenceInputStream(sequence stream)4.ObjectInputStream/ObjectOutputStream(object input and output stream)5.PrintStream(print stream)
Character stream
In Java, the input character stream ends with Reader, and the output character stream ends with Writer. For example, our common FileReader and FileWriter are character streams, and Reader and Witer are superclasses of input/output character streams, and are also abstract classes.
Commonly used character streams are:
1.FileReader/FileWriter2.BufferedReader/BufferedWriter3.InputStremReader/OutputStreamWriter(Convert Stream)
Convert flow
A conversion stream is a class that converts a byte stream into a character stream, and there are two types:
・InputStreamReader・OutputStreamWriter
InputStreamReader is a character stream (Reader), which requires wrapping a byte stream (InputStream);
OutputStreamWriter is a character stream (Writer), and needs to wrap a byte stream (OutputStream)
Decorate
The purpose of packaging is to add new functions on the basis of the original object. For example, the BufferedReader wraps a Reader, which is actually an enhancement of the Reader function; the original Reader can only be read by one character and one character, and the BufferedReader formed after packaging has a new function: the function of directly reading a line (readLine). Intuitively speaking, this is the so-called Decorate.
In terms of design mode, this is a typical decorative mode, and its characteristics are:
1. Decorative objects and real objects have the same interface. In this way, the client object can interact with the decorative object in the same way as the real object. 2. The decorative object can add some additional functions before or after forwarding these requests. This ensures that during runtime, additional functions can be added externally without modifying the structure of the given object.
Corresponding to us is that BufferedReader and Reader are both Readers. After packaging, the BufferedReader function is enhanced, but it can still be used as Readers (OO's parent class reference can point to subclasses)
example
Example of byte stream
Cut the mp3 file into multiple copies and recombine it
package cn.xdian.test;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.Enumeration;import java.util.Vector;public class Demo2 {public static void main(String[] args) throws IOException {cutFile();//Cut MP3 file mergeFlile();//Merge MP3 files}//Merge MP3public static void mergeFlile() throws IOException{File dir = new File("/home/gavinzhou/music_test");//Find all MP3 files in the folder Vector<FileInputStream> vector = new Vector<FileInputStream>();File[] files = dir.listFiles(); for (File file: files){if(file.getName().endsWith(".mp3")){vector.add(new FileInputStream(file));}}//Get the iterator through Vector Enumeration<FileInputStream> e = vector.elements();//Create a sequence stream SequenceInputStream inputStream = new SequenceInputStream(e);//Output stream FileOutputStream fileOutputStream = new FileOutputStream("/home/gavinzhou/conbine.mp3");//Read the split MP3 file byte[] buf = new byte[1024];int length = 0 ;while((length = inputStream.read(buf))!=-1){fileOutputStream.write(buf,0,length);}//Close the stream fileOutputStream.close();inputStream.close();}//Cut MP3public static void cutFile() throws IOException{File file = new File("/home/gavinzhou/test.mp3");File dir = new File("/home/gavinzhou/music_test");//Input byte stream FileInputStream fileInputStream = new FileInputStream(file);//Read the file byte[] buf = new byte[1024*1024];int length = 0;for (int i = 0 ; (length = fileInputStream.read(buf))!=-1 ; i++){FileOutputStream fileOutputStream = new FileOutputStream(new File(dir,"part"+i+".mp3"));fileOutputStream.write(buf,0,length);fileOutputStream.close();}//Close the stream fileInputStream.close();}}Example of character stream
Copy file A to file B
package cn.xidian.test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class Demo1 {public static void main(String[] args) throws IOException {File sourceFile = new File("/home/gavinzhou/a.txt");File desFile = new File("/home/gavinzhou/b.txt");//Create the input stream BufferedReader input = new BufferedReader(new FileReader(sourceFile));//Create the output stream BufferedWriter output = new BufferedWriter(new FileWriter(desFile));//Read the source file and write to the new file String line = null; while((line = input.readLine()) != null){output.write(line);output.newLine();}//Close the input and output stream input.close();output.close();}}Example of printing stream
package cn.xidian.test;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintStream;/*Print stream can print any type of data. Before printing the data, the data will be converted into a string and then printed*/class Animal{String name;String color;public Animal(String name,String color){this.name = name;this.color = color;}@Override public String toString() {return "Name:"+this.name+ " Color:"+ this.color;}}public class Demo6 {public static void main(String[] args) throws IOException {/* File file = new File("/home/gavinzhou/a.txt"); //Create a print stream PrintStream printStream = new PrintStream(file); //Print any information into the file printStream.println(97); printStream.println(3.14); printStream.println('a'); printStream.println(true); Animal a = new Animal("Rat", "Black"); printStream.println(a); //Change the standard input and output System.setOut(printStream); //Standard output is to the screen System.out.println("test...."); *///Collection of exception log information. File logFile = new File("/home/gavinzhou/test.log");PrintStream logPrintStream = new PrintStream( new FileOutputStream(logFile,true) );try{int c = 4/0;//Create an exception System.out.println("c="+c);int[] arr = null;System.out.println(arr.length);}catch(Exception e){e.printStackTrace(logPrintStream);//Output to file instead of on the screen}}}}Summarize
The above is all about io stream analysis and code examples in Java. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Java Exploration: Encrypted and decrypted code examples of Thread+IO files
Java IO stream related knowledge code analysis
Detailed interpretation of java IO stream
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!