In-depth analysis of the features and applications of I/O classes in Java

Source: Internet
Author: User

there are more than 40 classes in Java that are related to input and output, and it is not possible to use them flexibly without clearing the relationship between them.

If the flow from the stream to divide, can be divided into input and output streams, and the input and output streams can be divided into byte stream and character streams. The I/O stream in Java can thus be divided into:


Note that it is not an inheritance relationship, but just one.

Other classes related to I/O streaming in Java are actually inherited from the 4 base classes of Inputstream,reader,outputstream and writer. Where InputStream and OutputStream are byte streams, reader and writer are character streams.

This is because all of the data in the computer is binary, and the byte stream handles all binaries, but it is not possible to use a byte stream to process a text file, but it is more cumbersome, so there is usually a rule like this: if the input/output content is a text file, You should consider using a character stream, or you should consider using a byte stream if the input/output content is binary content (slices, audio files).

Here are the 4 base classes from Inputstream,reader,outputstream,writer, which list the commonly used subclasses:






The following description of the characteristics of each class and applicable occasions:

1. InputStreamReader and OutputStreamWriter are relatively special classes that convert a byte stream into a character stream, which is called a transform stream. such as InputStreamReader reader=new InputStreamReader (system.in);

Although the usage of 2.bufferedinputstream,bufferedoutputstream is the same as that of fileinputstream,fileoutputstream, but the efficiency is very different, Because the efficiency of the memory is much higher than the IO operation, the bufferedinputstream,bufferedoutputstream reads (writes) The contents of the file into the buffer in advance, and reads (writes) the buffer directly from the buffer if it exists. The new data is read (written) to the buffer only if there is no corresponding content in the buffer, and typically more data is requested. So when reading (writing) files, especially large files, do not use the simplest fileinputstream and fileoutputstream, but consider using Bufferedinputstream,bufferedoutputstream.

3.objectinputstream,objectoutputstream is to read/write to the file the serialized object (that is, the object that implements the Serializable interface), which is obviously the principle of using reflection.

4. As mentioned earlier, the difference between reader and InputStream is that one is a character input stream and one is a byte input stream. FileReader corresponds to FileInputStream, BufferedReader corresponds to Bufferedinputstream, so it is best to use BufferedReader instead of FileReader when reading a text file.

As Bytearrayinputstream and PipedInputStream are not commonly used, this article is not discussed at this stage.

Here are some code examples:

The first is to compare the original method of reading the file, that is, using FileInputStream:

This is an instance of the read byte stream public class Fileinputstreamsample {public static void main (String[]args) throws ioexception{ FileInputStream fis=new FileInputStream ("D://error.dat"); byte[]buff=new byte[1024];int HasRead=0;while (hasRead= Fis.read (Buff)) >0) {System.out.println (new String (Buff,0,hasread));}        Fis.close ();}}
The file is then written using FileOutputStream:

public class Fileoutputstreamsample {public static void main (String[]args) {String filename= "d://error.dat";// Note: You do not need to create a new one, because if you do not create it, it will be created by itself. String newfilename= "D://error2.txt"; try (FileInputStream fis=new fileinputstream (fileName); FileOutputStream fos=new FileOutputStream (newfilename)) {byte[]buff=new Byte[32];int hasRead=0;while (hasRead= Fis.read (Buff)) >0) {fos.write (buff,0,hasread);}} catch (IOException ex) {ex.printstacktrace ();}}}
A more efficient way to read files is to use Bufferedinputstream:

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 ();}}}
Here is a more efficient way to write to a file that uses Bufferedoutputstream:

public class Bufferedoutputstreamsample {public static void main (String[]args) {String content= "I had a dream"; File File=new file ("D://dream.dat"); Byte[]buff=content.getbytes (); try (Bufferedoutputstream bos=new Bufferedoutputstream (file);) {    bos.write (buff);    In addition, BOS has a method of Bos.write (Byte[],int arg1,int arg2);}    catch (IOException ex)    {    ex.printstacktrace ();}}    }
Here's how filereader is used, but note that filereader reading a text file is a relatively inefficient approach:

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 way to write to a text file:

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 th e Sons of  former slave owner would be able to sit down together at the table.\n "); Fw.write (" My Four little children wil L One day live in a nation where they'll is not being judged by the color of their skins but by the content of their character. \ n ");} catch (IOException ex) {ex.printstacktrace ();}}}
BufferedReader is a more efficient way to read a text file, but note that its construction requires a inputstreamreader, and Inpustreamreader is the packaging fileinputstream, So the use of BufferedReader is as follows:

public class Bufferedreadersample {public static void main (String[]args) {try (//InputStreamReader reader=new If the file is read) 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.readline ())!=null)      {      System.out.println (buffer.touppercase ());}      } catch (IOException ex) {ex.printstacktrace ();}}}

Obviously, the advantage of BufferedReader is that it can read one line of text at a time----with a newline character as a flag, the above example is converted to uppercase after reading the keyboard input and output, of course, you can also read the file after converting the lines to uppercase after the output.

BufferedWriter usage is simpler, but it is worth noting that it is flush:

public class Bufferedwritersample {public static void main (String[]args) {try (     ///If write to file is OutputStreamWriter Writer=new OutputStreamWriter (New FileOutputStream ("D://error.dat"));     OutputStreamWriter writer=new OutputStreamWriter (System.out); BufferedWriter bw=new BufferedWriter (writer);) {String content= "less are more\nless is-more are not a law\nless are more are no T always correct "; bw.write (content); Bw.flush ();} catch (IOException ex) {ex.printstacktrace ();}}}

The following is a comparison of the 3 classes of Printstream,printwriter,bufferedwriter:

First, they have something in common: they are all processing streams (wrapper streams) rather than node streams, making them easier to use, such as PrintStream using the println (string) function, bufferedwriter using the writer (string) function;

The difference between PrintStream and Printwriter,bufferedwriter is that the former deals with the byte stream, and the latter is the process of the character stream, whereas BufferedWriter is compared with printwriter because of the buffer function. Its efficiency is higher than printwriter.

Here is an example of a 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 will take the previous overlay, if you want not to overwrite it, it is necessary to use the Ps.append method instead of the Println method. Ps.println ("Less are more");//Use the PRINTLN output object directly, which is useful in socket programming. Ps.println (New Student ());} catch (IOException ex) {ex.printstacktrace ();}}}
Here 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 ("not more than is a important rule."); Writer.println (TRUE);} }}

Finally, ObjectInputStream and ObjectOutputStream, using these two classes to read and write serialized objects is particularly handy, 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");//This shows that Bufferedinputstream and ObjectOutputStream are actually packaging FileOutputStream. Try (ObjectOutputStream oos=new objectoutputstream (new FileOutputStream (file)) {oos.writeobject (STU1); o Os.writeobject (STU2);} catch (IOException ex) {ex.printstacktrace ();}}} Class Student implements Serializable{private int id;private string name;private string address;public Student (int id,str ing 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 ();}}}

















In-depth analysis of the features and applications of I/O classes in Java

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.