Summary of IO streams in Java

Source: Internet
Author: User

This article is in the study summary, welcome reprint but please specify Source: http://write.blog.csdn.net/postedit/42119261


I think you have a good understanding of Java IO Stream, usually use more, but for its specific classification and inheritance system may not know much, may also rarely go to the relevant API documentation, find out the relationship and the respective application situation. This paper simply classifies the commonly used IO streams, and gives a simple example to illustrate their applications. I hope this article will be of some help to you.


(A) The IO stream is broadly divided into two types:

(1) byte stream: the corresponding abstract class is inputstream (input stream) and OutputStream (output stream).
(2) Character stream: the corresponding abstract class is reader (input stream) and writer (output stream).

(B) The specific implementation is as follows :

(1) Byte stream: (commonly used) FileInputStream realizes the InputStream.
The OutputStream (common) implements the FileOutputStream.
(2) Character stream: (commonly used) BufferedReader, InputStreamReader, StringReader realized Reader,filereader inherited InputStreamReader.
(commonly used) BufferedWriter, outputstreamwriter, StringWriter realized Writer,filewriter inherited OutputStreamWriter.

(C) The implementation of the class details and the use of the following:


Output stream:

(1) OutputStreamWriter is a bridge of character flow to a byte stream: encodes the character to be written to bytes using the specified charset. The character set it uses can be specified by name or explicitly given, otherwise the platform default character set may be accepted. Each call to the write () method invokes the encoding converter for the given character (or character set). The resulting bytes are accumulated in the buffer before they are written to the underlying output stream. You can specify the size of this buffer, but the default buffer is large enough for most purposes. For maximum efficiency, consider wrapping the outputstreamwriter in BufferedWriter to avoid frequent calls to the converter. For example:
BufferedWriter out = new BufferedWriter (new OutputStreamWriter (System.out));

(2) FileReader is a convenient class for reading character files to read stream of characters.

(3) BufferedReader has buffers that read text from the character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and rows.

(4) StringReader the character input stream of a string.

(5) FileInputStream to read the original byte stream. Commonly used for reading binary files, slices, sounds, images and other files.


Input stream:

(1) InputStreamReader is a bridge of byte flow to a character stream: it reads the bytes with the specified charset and decodes them to characters. Each call to its one read () method causes one or more bytes to be read from the underlying input stream. To enable a valid conversion from byte to character, you can read more bytes in advance from the underlying stream so that it exceeds the bytes required to satisfy the current read operation. In order to achieve maximum efficiency, it is necessary to consider packaging InputStreamReader within the BufferedReader. For example: BufferedReader in = new BufferedReader (new InputStreamReader (system.in));

(2) FileWriter a convenient class for writing character files.

(3) BufferedWriter has buffers that write text to the character output stream, buffering individual characters, providing efficient writes of individual characters, arrays, and strings.

(4) StringWriter a character output stream of a string, which can be used to construct a string by reclaiming the output in a string buffer.

(5) FileOutputStream writes the original byte stream. Commonly used for reading binary files, slices, sounds, images and other files.


(D) The code example analysis is as follows:

Import Java.io.bufferedreader;import java.io.bufferedwriter;import java.io.file;import java.io.FileInputStream; Import Java.io.fileoutputstream;import java.io.filereader;import java.io.filewriter;import java.io.IOException; Import Java.io.inputstream;import Org.junit.test;public class Teststream {//Read characters in file @testpublic void Testread () throws I oexception {String Path = "Read.txt"; FileReader read = new FileReader (path); BufferedReader reader = new BufferedReader (read); while (reader.readline () = null) {String s = reader.readline (); System.err.println (s);} Reader.close ();} Write character to file @testpublic void Testwrite () throws IOException {String path = "Write.txt"; FileWriter write = new FileWriter (path); BufferedWriter writer = new BufferedWriter (write), char[] buffer = new Char[1024];for (int i = 0; i < 1024x768; i++) {if (c har) ' A ' + i > Character.max_value) {buffer[i] = ' Z '; SYSTEM.ERR.PRINTLN (1);} else {Buffer[i] = (char) (' a ' + i);}} Writer.write (buffer); Writer.close ();} Delete file contents @testpublic void TeStdelete () throws IOException {String path = "Write.txt"; FileWriter write = new FileWriter (path); BufferedWriter writer = new BufferedWriter (write); StringBuffer buffer = new StringBuffer (); Writer.write (buffer.tostring ()); Writer.close ();} Replace content @testpublic void Testdeleteandreplace () throws IOException {String path = "Write.txt"; FileWriter write = new FileWriter (path); BufferedWriter writer = new BufferedWriter (write); int i = 0;while (++i <) {StringBuffer buffer = new StringBuffer () ; Buffer.append (Math.random ()); Writer.write (buffer.tostring () + "\ r \ n");} Writer.close ();}            Copy one file contents to another file @testpublic void CopyFile (String oldpath, String NewPath) {try {int byteread = 0;            File Oldfile = new file (OldPath);      if (oldfile.exists ()) {//file exists InputStream instream = new FileInputStream (OldPath);                Read in the original file FileOutputStream fs = new FileOutputStream (NewPath); byte[] buffer = new BYTE[100]; WhIle ((Byteread = instream.read (buffer))! =-1) {fs.write (buffer, 0, byteread);                } instream.close ();           Fs.close ();        }} catch (Exception e) {e.printstacktrace (); }}//read character stream @testpublic static void Testreadbyte () {String path = "Write.txt"; File File = new file (path); InputStream in = null;try {//read one byte in = new FileInputStream (file); int Tempbyte;while (tempby Te = In.read ())! =-1) {System.out.write (tempbyte);} In.close ();} catch (IOException e) {e.printstacktrace (); return;} try {//Read multiple bytes byte[] tempbytes = new Byte[100];int Byteread = 0;in = new FileInputStream (path); while (Byteread = In.read (tempbytes)) ! =-1) {System.out.write (tempbytes, 0, Byteread);}} catch (Exception E1) {e1.printstacktrace ();} finally {if (in! = null) {try {in.close ();} catch (IOException e1) {}}}}

Summary of IO streams 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.