In-depth analysis of Java I/O class features and application scenarios, in-depth analysis of application scenarios
There are more than 40 classes related to input and output in Java. If the relationship between them is not clarified, they cannot be used flexibly.
If the stream flow is divided, it can be divided into the input stream and the output stream, and the input stream and the output stream can be divided into byte stream and two streams. Therefore, I/O streams in Java can be divided:
Note that it is not an inheritance relationship, but.
Other classes related to I/O Stream processing in Java are actually inherited from the four base classes InputStream, Reader, OutputStream, and Writer. InputStream and OutputStream are byte streams, and Reader and Writer are bytes streams.
The reason for this division is that all data in the computer is binary, and byte streams can process all binary files. However, if byte streams are used to process text files, it is not impossible, but it will be more troublesome, so it is generally like the next rule: if the input/output content is a text file, you should consider using the ghost stream; if the input/output content is binary (slice or audio file), byte streams should be considered.
The following describes four base classes, InputStream, Reader, OutputStream, and Writer, and lists common subclasses:
The following describes the features and application scenarios of each category:
1. InputStreamReader and OutputStreamWriter are special classes. They can exchange byte streams into bytes streams. Therefore, they are called conversion streams. For example, InputStreamReader reader = new InputStreamReader (System. in );
2. the usage of BufferedInputStream and BufferedOutputStream is the same as that of FileInputStream and FileOutputStream, but the efficiency is quite different, because the memory efficiency is much higher than the IO operation efficiency, while BufferedInputStream, bufferedOutputStream reads (writes) the content in the file to the buffer zone in advance. When reading (writing), if the buffer zone exists, it reads directly from the buffer zone, new data is read (written) to the buffer zone only when there is no corresponding content in the buffer zone, and more data is usually requested. Therefore, when reading (writing) files, especially large files, do not use the simplest FileInputStream and FileOutputStream, but use BufferedInputStream and BufferedOutputStream.
3. ObjectInputStream and ObjectOutputStream read/write serialized objects (objects that implement the Serializable Interface) to the file. Obviously, this actually uses the reflection principle.
4. As mentioned earlier, the difference between Reader and InputStream is that one is a character input stream and the other is a byte input stream. FileReader corresponds to FileInputStream, and BufferedReader corresponds to BufferedInputStream. Therefore, it is best to use BufferedReader instead of FileReader when reading text files.
This article does not discuss ByteArrayInputStream and PipedInputStream.
Below are some code examples:
The first is the original method for reading files, that is, using FileInputStream:
// This is the instance for reading the byte stream. public class FileInputStreamSample {public static void main (String [] args) throws IOException {FileInputStream FS = new FileInputStream ("d: // error. dat "); byte [] buff = new byte [1024]; int hasRead = 0; while (hasRead = Fi. read (buff)> 0) {System. out. println (new String (buff, 0, hasRead);} fiis. close ();}}
Then, use FileOutputStream to write files:
Public class FileOutputStreamSample {public static void main (String [] args) {String fileName = "d: // error. dat "; // Note: you do not need to create a new one in advance, because it will create a new one if it is not created. String newFileName = "d: // error2.txt"; try (FileInputStream FD = new FileInputStream (fileName); FileOutputStream fos = new FileOutputStream (newFileName )) {byte [] buff = new byte [32]; int hasRead = 0; while (hasRead = Fi. read (buff)> 0) {fos. write (buff, 0, hasRead) ;}} catch (IOException ex) {ex. printStackTrace ();}}}
You can use BufferedInputStream to efficiently read files:
public class BufferedInputStreamSample {public static void main(String[]args){File file=new File("d://error.dat");try(BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));){ byte[]buff=new byte[1024]; int hasRead=0; while((hasRead=bis.read(buff))>0) { String content=new String(buff,0,hasRead); System.out.println(content); }}catch(IOException ex){ex.printStackTrace();}}}
The following is a more efficient method for writing files, that is, using BufferedOutputStream:
Public class BufferedOutputStreamSample {public static void main (String [] args) {String content = "I have a dream"; File file = new File ("d: // dream. dat "); byte [] buff = content. getBytes (); try (BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (file);) {bos. write (buff); // In addition, the bos method is bos. write (byte [], int arg1, int arg2);} catch (IOException ex) {ex. printStackTrace ();}}}
The following describes how to use FileReader. However, it is inefficient to read a text file using FileReader:
public class FileReaderSample {public static void main(String[]args){try(FileReader fr=new FileReader("d://error.dat")){char[]cbuff=new char[32];int hasRead=0;while((hasRead=fr.read(cbuff))>0){System.out.println(new String(cbuff,0,hasRead));}}catch(IOException ex){ex.printStackTrace();}}}
Similarly, FileWriter is a relatively inefficient method for writing text files:
public class FileWriterSample {public static void main(String[]args){try(FileWriter fw=new FileWriter("d://poem.txt")){fw.write("I have a dream\n");fw.write("One day on the red hills of Georgia\n");fw.write("The sons of former slaves and the sons of former slave owner will be able to sit down together at the table.\n");fw.write("My four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character.\n");}catch(IOException ex){ex.printStackTrace();}}}
BufferedReader is a more efficient way to read text files, but note that its construction method requires an InputStreamReader, and InpuStreamReader is packaged with FileInputStream. Therefore, BufferedReader is used as follows:
Public class BufferedReaderSample {public static void main (String [] args) {try (// if the object is read, it is InputStreamReader reader = new InputStreamReader (new InputStream ("d: // error. dat "); // InputStreamReader reader = new InputStreamReader (new FileInputStream (" d: // error. dat "); InputStreamReader reader = new InputStreamReader (System. in); BufferedReader br = new BufferedReader (reader) {String buffer = null; while (buffer = br. re AdLine ())! = Null) {System. out. println (buffer. toUpperCase () ;}} catch (IOException ex) {ex. printStackTrace ();}}}
Obviously, BufferedReader has a buffer function. It can read a line of text at a time, marked by a line break. In the above example, it reads the keyboard input and converts it to uppercase and outputs. Of course, you can also read the file and convert each row into uppercase and then output it.
BufferedWriter is easy to use, but it should be noted that it should be flush:
Public class BufferedWriterSample {public static void main (String [] args) {try (// if it is written to a file, it is OutputStreamWriter writer = new OutputStreamWriter (new FileOutputStream ("d: // error. dat "); OutputStreamWriter writer = new OutputStreamWriter (System. out); BufferedWriter bw = new BufferedWriter (writer);) {String content = "Less is more \ nLess is more is not a law \ nLess is more is not always correct "; bw. write (content); bw. flush ();} catch (IOException ex) {ex. printStackTrace ();}}}
The following is a comparison between PrintStream, PrintWriter, and BufferedWriter classes:
First, they all share the same thing: They are processing streams (Packaging streams) rather than node streams, so they can be used more conveniently. For example, PrintStream uses the println (String) function, and BufferedWriter uses writer (String) function;
The difference between PrintStream and PrintWriter and BufferedWriter is that the former processes byte streams, while the latter processes two bytes streams. Compared with PrintWriter, BufferedWriter is more efficient than PrintWriter because of the buffer.
The following is an example of PrintStream:
Class Student {int id; String name; public Student () {id = 0; name = "Jenny";} public String toString () {return "id =" + id + "name =" + name ;}} public class PrintStreamSample {public static void main (String [] args) {String fileName = "d: // poem.txt "; try (PrintStream ps = new PrintStream (new FileOutputStream (fileName) {// Note: This overwrites the previous one. To avoid overwriting, use ps. the append method is not the println method. Ps. println ("Less is more"); // directly use println to output objects, which is useful in Socket programming. Ps. println (new Student ();} catch (IOException ex) {ex. printStackTrace ();}}}
The following is an example of PrintWriter:
public class PrintWriterSample {public static void main(String[]args){try(PrintWriter writer=new PrintWriter(new OutputStreamWriter(System.out));){writer.println("Less is more is a important rule.");writer.println(true);} }}
Finally, ObjectInputStream and ObjectOutputStream are used to read and write serialized objects conveniently, as shown below:
Public class ObjectOutputStreamSample {public static void main (String [] args) {Student stu1 = new Student (1, "Jack", "NewYork"); Student stu2 = new Student (2, "Rose", "California"); File file = new File ("d: // object.txt"); // it can be seen that BufferedInputStream and ObjectOutputStream are actually packaging FileOutputStream. Try (ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (file) {oos. writeObject (stu1); oos. writeObject (stu2);} catch (IOException ex) {ex. printStackTrace () ;}} class Student implements Serializable {private int id; private String name; private String address; public Student (int id, String name, String address) {this. id = id; this. name = name; this. address = address ;}@ Overridepublic String toString () {StringBuilder sb = new StringBuilder (); sb. append ("id:" + id); sb. append (""); sb. append ("name:" + name); sb. append (""); sb. append ("address:" + address); return sb. toString ();}}
public class ObjectInputStreamSample {public static void main(String[]args){File file=new File("d://object.txt");try(ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file))){Student stu1=(Student)ois.readObject();Student stu2=(Student)ois.readObject();}catch(Exception ex){ex.printStackTrace();}}}