Java IO Stream Learning Summary

Source: Internet
Author: User
Tags file copy readfile

Java IO Stream Learning Summary one: input and output stream

Reprint please indicate source: http://blog.csdn.net/zhaoyanjun6/article/details/54292148
This article is from "Zhaoyan's blog"

Java Flow class diagram structure:

Concept and function of flow

A stream is a set of sequences of bytes that have a starting point and an end point, a generic or abstract of the data transfer. That is, the transmission of data between the two devices is called the flow, the essence of the flow is data transmission, according to the data transmission characteristics of the stream abstracted into various classes, convenient and more intuitive data manipulation.

Classification of IO Streams
    • Divided into: character stream and byte stream according to different types of processing data
    • Divided into: input stream and output stream according to data flow
Character Stream and Byte stream

The origin of a character stream: Because of the difference in data encoding, there is a stream object that efficiently operates on characters. The essence is actually based on the byte stream reading, to check the specified code table. The difference between a byte stream and a character stream:

    • Read-write units are different: byte stream in bytes (8bit), character stream in characters, according to the Code table mapping characters, one can read multiple bytes at a time.
    • The processing object is different: The byte stream can handle all types of data (slices, AVI, etc.), while the character stream can only handle data of the type of characters.

    • BYTE stream: A read-in or read-out is a 8-bit binary.
    • Character Stream: A read-in or read-out is a 16-bit binary.

The data on the device is stored in binary, whether it is a picture or video, or text. The binary is ultimately represented by a 8-bit data unit, so the smallest data unit in the computer is the byte. means that the byte stream can handle all the data on the device, so the byte stream can handle character data as well.

conclusion: As long as you are working with plain text data, you will prefer to use character streams. In addition, byte streams are used. Input stream and output stream

The input stream can only be read, the output stream can only write, and the program needs to use different streams depending on the characteristics of the data being transmitted.

Input byte stream InputStream
    • InputStreamis the parent class for all input byte streams, which is an abstract class.
    • ByteArrayInputStream, StringBufferInputStream FileInputStream is three basic media streams, which Byte 数组 StringBuffer read data from,,, and 本地文件 in each.
    • PipedInputStreamis to read data from a pipeline that is shared with other threads, followed by a separate description of piped-related knowledge.
    • ObjectInputStreamAnd all FilterInputStream subclasses are decorative streams (the protagonist of the adorner pattern).
Output byte stream outputstream
    • OutputStreamis the parent class of all output byte streams, which is an abstract class.
    • ByteArrayOutputStream, FileOutputStream is two basic media streams, which Byte 数组 write data to, and, respectively 本地文件 .
    • PipedOutputStreamis to write data to a pipeline that is shared with other threads.
    • ObjectOutputStreamAnd all FilterOutputStream subclasses are decorative streams.

Summarize:

    • Input stream: InputStream or reader: read from the file to the program;
    • Output stream: OutputStream or Writer: output from the program to a file;
Node stream

Node stream: Directly connected to the data source, read in or read out.
Direct use of node flow, read and write inconvenient, in order to read and write files faster, only the processing stream.

Common node streams
    • Parent class: InputStream , OutputStream , Reader ,Writer
    • File:,,, FileInputStream FileOutputStrean FileReader FileWriter file to process the node stream
    • Arrays:,,, array of ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter nodes to be processed by the stream (the corresponding is no longer a file, but an array in memory)
    • String: StringReader a StringWriter node stream that processes a string
    • Pipeline:,,, PipedInputStream PipedOutputStream PipedReader PipedWriter node flow for pipeline processing
Process Flow

The processing stream and the node stream are used together, on the basis of the node flow, and then one layer is connected, and the socket is on the node stream. BufferedReaderFor example, the construction method of a process flow always takes an additional stream object to do the argument. A Stream object passes through multiple wrappers of other streams, called links to streams.

Common flow of processing
    • Buffer stream:,,, BufferedInputStrean BufferedOutputStream BufferedReader BufferedWriter add buffering function, avoid frequently read and write hard disk.
    • Convert stream: InputStreamReader , OutputStreamReader implements the conversion between the byte stream and the character stream.
    • Data flow: DataInputStream , DataOutputStream et-provides the writing of the underlying data type to a file, or read it.
Convert stream

InputStreamReader, OutputStreamWriter InputStream or OutputStream as a parameter, to convert from a stream of bytes to a stream of characters.

constructor function

InputStreamReader(InputStream);        //通过构造函数初始化,使用的是本系统默认的编码表GBK。InputStreamWriter(InputStream,String charSet);   //通过该构造函数初始化,可以指定编码表。OutputStreamWriter(OutputStream); //通过该构造函数初始化,使用的是本系统默认的编码表GBK。OutputStreamwriter(OutputStream,String charSet); //通过该构造函数初始化,可以指定编码表。
Practical Walkthrough
    • Use of the FileInputStream class: Read file contents
Package Com.app;Import Java.io.FileInputStream;Import java.io.FileNotFoundException;Import java.io.IOException;PublicClassA1 {PublicStaticvoidMain(string[] args) {A1 A1 =New A1 ();Abc.txt document in Computer D drive String FilePath ="D:/abc.txt"; String Reslut = A1.readfile (FilePath); System.out.println (Reslut); }/** * Read the contents of the specified file *@param filePath: path to File *The result of @return return */Public StringReadFile(String FilePath) {FileInputStream fis=Null String result ="" ;try {Instantiating an input stream object based on path path FIS =New FileInputStream (FilePath);2. Returns the estimated value of the remaining bytes bytes that can be read in this input stream;int size = fis.available (); //3. Creates a byte array based on the number of bytes in the input stream; byte[] array = new byte[size]; //4. Reads the data into the array; fis.read (array); //5. Creates a new string based on the obtained byte array and outputs it; result = new string (array);} Span class= "Hljs-keyword" >catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally{if (fis! = null) {try {fis.close ();} catch (IOException e) {e.printstacktrace ();}} } return result;}}           
    • Use of the FileOutputStream class: Writing content to a file
Package Com.app;Import java.io.FileNotFoundException;Import Java.io.FileOutputStream;Import java.io.IOException;PublicClassA2 {PublicStaticvoidMain(string[] args) {A2 A2 =New A2 ();Abc.txt document in Computer D drive String FilePath ="D:/abc.txt";What to write String content ="Today is 2017/1/9, the weather is very good"; A2.writefile (FilePath, content); }/** * Create output stream based on file path *@param filePath: path to File *@param content: What you need to write */Publicvoidwritefile (string filePath, string content) {FileOutputStream fos = null; try {//1, creating output stream based on file path FOS = new FileOutputStream (FilePath); //2, converts string to byte array, byte[] array = content.getbytes (); Span class= "Hljs-comment" >//3, byte array output; Fos.write (array); } catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally{if (fos! = null) {try {fos.close ();} catch (IOException e) {e.printstacktrace ();}} } }}

Attention:

    1. In a real project, all IO operations should be placed in a sub-thread to avoid blocking the main thread.
    2. FileInputStreamWhen we read the contents of the file, we pass in the path of the file ( "D:/abc.txt" ), and if the file does not exist in the path, the readFile() exception is reported when the method is executed FileNotFoundException .
    3. FileOutputStreamWhen we write to the file, we pass the path to the file ( "D:/abc.txt" ), and if the file does not exist in the path, writeFile() we will create a new file by default when we execute the method. There is also an important point that does not report anomalies.

    • Comprehensive exercises to copy files, copy from D disk to E drive
Package Com.app;Import Java.io.FileInputStream;Import java.io.FileNotFoundException;Import Java.io.FileOutputStream;Import java.io.IOException;PublicClassA3 {PublicStaticvoidMain(string[] args) {A3 A2 =New A3 ();The path of the Cat.png picture in the computer D drive String filePath1 ="D:/cat.png";The path to the Cat.png picture in the E-drive of the computer String filePath2 ="E:/cat.png";Copy file A2.copyfile (filePath1, filePath2); }/** * File Copy *@param filepath_old: The path of the file to be copied *@param filepath_new: The path where the files are copied */PublicvoidCopyFile(String filepath_old, String filepath_new) {FileInputStream fis=null; FileOutputStream Fout =null;try {Instantiating an input stream object based on path path FIS =New FileInputStream (Filepath_old);2. Returns the estimated value of the remaining bytes bytes that can be read in this input stream;int size = fis.available ();3. Creates a byte array based on the number of bytes in the input stream;byte[] Array =Newbyte[size]; //4. Reads the data into the array; fis.read (array); //5, create output stream according to file path Fout = new FileOutputStream (filepath_new); Span class= "Hljs-comment" >//5, byte array output; Fout.write (array); } catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally{if (fis! = null) {try {fis.close ();} catch (IOException e) {e.printstacktrace ();}} if (fout! = null) {try {fout.close (); } catch (IOException e) {e.printstacktrace ();}}} }}

Java IO Stream Learning summary

Related Article

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.