Java Common IO Stream operation detailed

Source: Internet
Author: User
Tags readline

1. Basic Concepts

Io:java the operation of the data is through the flow, IO flow is used to process the data transfer between the devices, upload files and download files, Java for the operation of the flow of objects are in the IO package.

Classification of 2.IO Streams

Diagram: (Primary IO stream)

3. Byte stream (1). Byte stream base class 1). InputStream

InputStream: Byte input stream base class, which is a superclass of all classes that represent byte input streams.

 常用方法:    // 从输入流中读取数据的下一个字节    abstract int read()    // 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b中    int read(byte[] b)    // 将输入流中最多 len 个数据字节读入 byte 数组    int read(byte[] b, int off, int len)    // 跳过和丢弃此输入流中数据的 n个字节    long skip(long n)    // 关闭此输入流并释放与该流关联的所有系统资源    void close()
2). OutputStream

OutputStream: Byte output stream base class, abstract class is a superclass of all classes that represent output byte streams.

 常用方法:    // 将 b.length 个字节从指定的 byte 数组写入此输出流    void write(byte[] b)    // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流    void write(byte[] b, int off, int len)    // 将指定的字节写入此输出流    abstract void write(int b)    // 关闭此输出流并释放与此流有关的所有系统资源    void close()    // 刷新此输出流并强制写出所有缓冲的输出字节    void flush()
(2). Byte file operation flow 1). fileinputstream

FileInputStream: A byte file input stream that obtains input bytes from a file in the file system for reading raw byte streams such as data.

 构造方法:    // 通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的File对象file指定    FileInputStream(File file)    // 通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的路径name指定    FileInputStream(String name) 常用方法:覆盖和重写了父类的的常用方法。
 //read the file under F disk f://hell/test.txt / /Construction Method 1 InputStream inputstream = new fileinputstream (new File ( "f://hello//test.txt")); int i = 0; //reads one byte at a time while ((i = Inputstream.read ())! =-1" {//System.out.print (i + "");//All in all, //why Will output 65 66 67 68? Because characters are stored at the bottom of the stored value. The ASCII code that corresponds to the character. System. out.print ((char) i + //A B C D} //close io stream inputstream.close ();     
        //read the file under F disk f://hell/test.txt //construction Method 2 InputStream input        STREAM2 = new fileinputstream ( "F://hello/test.txt"); //byte array byte[] b = new byte[2]; int i2 = 0; //reads one byte array at a time while ((I2 = Inputstream2.read (b))! =-1) {system.new String (b, 0, I2) +  ") ; //AB CD} //close io stream inputstream2.close ();          

Note: Reading one byte array at a time improves operational efficiency and must be closed when the IO stream is used.

2). FileOutputStream

FileOutputStream: The byte file output stream is used to write data to file, which is written from the program to another location.

 构造方法:    // 创建一个向指定File对象表示的文件中写入数据的文件输出流    FileOutputStream(File file)    // 创建一个向指定File对象表示的文件中写入数据的文件输出流    FileOutputStream(File file, boolean append)    // 创建一个向具有指定名称的文件中写入数据的输出文件流    FileOutputStream(String name)    // 创建一个向具有指定name的文件中写入数据的输出文件流    FileOutputStream(String name, boolean append) 常用方法:覆盖和重写了父类的的常用方法。
 OutputStream outputstream = new fileoutputstream (new File (" test.txt ")); //writes out data outputstream.write ( "ABCD". GetBytes ()); //close io stream outputstream. close (); //content append write OutputStream outputStream2 = new FileOutputStream ( Span class= "hljs-string" > "test.txt", true); //output line break outputstream2.write ( "\ r \ n". GetBytes ()); //output append content outputstream2.write ( "Hello". GetBytes ()); //close io stream outputStream2. close ();             

Note: The output destination file does not exist, it will be automatically created, do not specify a drive letter, the default is created in the project directory; output line breaks must be written \ r \ n cannot be written \ n, because different text editors differ in the recognition of line characters.

(3). Byte buffer stream (high flow) 1). Bufferedinputstream

Bufferedinputstream: Byte buffered input stream for improved read efficiency.

     构造方法:     // 创建一个 BufferedInputStream并保存其参数,即输入流in,以便将来使用。     BufferedInputStream(InputStream in)     // 创建具有指定缓冲区大小的 BufferedInputStream并保存其参数,即输入流in以便将来使用     BufferedInputStream(InputStream in, int size)
InputStream in =new fileinputstream ( "test.txt"); //byte cache stream Bufferedinputstream bis = new bufferedinputstream (i n); byte[] bs = new byte[20]; int len = 0; while (len = Bis.read (BS))!=-1) {System.out. Print (new String (Bs, 0, len)); Span class= "hljs-comment" >//ABCD //Hello} //Close stream Bis.close ();              
2). Bufferedoutputstream

Bufferedoutputstream: Byte buffered output stream for improved writing efficiency.

     构造方法:     // 创建一个新的缓冲输出流,以将数据写入指定的底层输出流     BufferedOutputStream(OutputStream out)     // 创建一个新的缓冲输出流,以将具有指定缓冲区大小的数据写入指定的底层输出流     BufferedOutputStream(OutputStream out, int size)     常用方法:     // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流     void write(byte[] b, int off, int len)     // 将指定的字节写入此缓冲的输出流     void write(int b)     // 刷新此缓冲的输出流     void flush()
        new BufferedOutputStream(new FileOutputStream("test.txt", true));        // 输出换行符 bos.write("\r\n".getBytes()); // 输出内容 bos.write("Hello Android".getBytes()); // 刷新此缓冲的输出流 bos.flush(); // 关闭流 bos.close();
4. Character stream (1). Character stream base class 1). Reader

Reader: An abstract class that reads a stream of characters.

  常用方法:    // 读取单个字符    int read()    // 将字符读入数组    int read(char[] cbuf)    // 将字符读入数组的某一部分    abstract int read(char[] cbuf, int off, int len)    // 跳过字符    long skip(long n)    // 关闭该流并释放与之关联的所有资源    abstract void close()
2). Writer

Writer: abstract class that writes a stream of characters.

 常用方法:    // 写入字符数组     void write(char[] cbuf)    // 写入字符数组的某一部分    abstract void write(char[] cbuf, int off, int len)    // 写入单个字符    void write(int c)    // 写入字符串    void write(String str)    // 写入字符串的某一部分    void write(String str, int off, int len)    // 将指定字符添加到此 writer    Writer append(char c)    // 将指定字符序列添加到此 writer    Writer append(CharSequence csq)    // 将指定字符序列的子序列添加到此 writer.Appendable    Writer append(CharSequence csq, int start, int end)    // 关闭此流,但要先刷新它    abstract void close()    // 刷新该流的缓冲    abstract void flush()
(2). Character conversion stream 1). InputStreamReader

InputStreamReader: A stream of byte-flow characters that uses a character set that can be specified by name or explicitly given, otherwise the platform default character set will be accepted.

 构造方法:    // 创建一个使用默认字符集的 InputStreamReader    InputStreamReader(InputStream in)    // 创建使用给定字符集的 InputStreamReader    InputStreamReader(InputStream in, Charset cs)    // 创建使用给定字符集解码器的 InputStreamReader    InputStreamReader(InputStream in, CharsetDecoder dec)    // 创建使用指定字符集的 InputStreamReader    InputStreamReader(InputStream in, String charsetName) 特有方法:    //返回此流使用的字符编码的名称     
        Using the default encoding inputstreamreader reader =New InputStreamReader (New FileInputStream ("Test.txt"));IntLen while ((len = Reader.read ())!=-1) {System.out.print ((char) len); close (); //specify encoding InputStreamReader reader = new InputStreamReader ( Span class= "hljs-built_in" >new fileinputstream ( "test.txt"), int len; while (len = Reader.read ())!=-1) {System.out. Print ((char) len); close ();             

Note: Eclipse uses GBK encoding by default, so the Test.txt file is GBK encoded and is garbled when the UTF-8 encoding is specified.

2). OutputStreamWriter

OutputStreamWriter: A stream of byte-flow characters.

 构造方法:    // 创建使用默认字符编码的 OutputStreamWriter    OutputStreamWriter(OutputStream out)    // 创建使用给定字符集的 OutputStreamWriter    OutputStreamWriter(OutputStream out, Charset cs)    // 创建使用给定字符集编码器的 OutputStreamWriter    OutputStreamWriter(OutputStream out, CharsetEncoder enc)    // 创建使用指定字符集的 OutputStreamWriter    OutputStreamWriter(OutputStream out, String charsetName) 特有方法:    //返回此流使用的字符编码的名称     
(3). Character Buffer stream (high flow) 1). BufferedReader

BufferedReader: A character buffer stream that reads text from the character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and rows.

 构造方法:    // 创建一个使用默认大小输入缓冲区的缓冲字符输入流    BufferedReader(Reader in)    // 创建一个使用指定大小输入缓冲区的缓冲字符输入流    BufferedReader(Reader in, int sz) 特有方法:    // 读取一个文本行    String readLine()
        //生成字符缓冲流对象        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"))); String str; //一次性读取一行 while ((str = reader.readLine()) != null) { System.out.println(str);// 爱生活,爱Android } //关闭流 reader.close();
2). BufferedWriter

BufferedWriter: A character buffer stream that writes text to a character output stream, buffering individual characters, providing efficient writes of a single character, array, and string.

 构造方法:    // 创建一个使用默认大小输出缓冲区的缓冲字符输出流    BufferedWriter(Writer out)    // 创建一个使用给定大小输出缓冲区的新缓冲字符输出流    BufferedWriter(Writer out, int sz) 特有方法:    // 写入一个行分隔符    
(4). FileReader, FileWriter
 FileReader:InputStreamReader类的直接子类,用来读取字符文件的便捷类,使用默认字符编码。 FileWriter:OutputStreamWriter类的直接子类,用来写入字符文件的便捷类,使用默认字符编码。
5. Efficient ratio of flow efficiency
读取f盘下的一个视频文件到项目中:文件大小29.5 MB
Read mode one:
FileInputStream InputStream =New FileInputStream ("f://skateboard//heel_flip.mp4");        FileOutputStream outputstream = new FileOutputStream ("Heel_flip.mp4"); int Len; //start time long begin = System.currenttimemillis (); //read one byte at a time (len = Inputstream.read ()) ! =-1) {outputstream.write (len);} //milliseconds System.out. println (System.currenttimemillis ()-begin); //213195 //Close Stream release resource InputStream.  Close (); OutputStream. close ();                
Read mode two:
FileInputStream InputStream =New FileInputStream ("f://skateboard//heel_flip.mp4"); FileOutputStream OutputStream =new fileoutputstream ( "Heel_flip.mp4"); int len; byte[] bs = new byte[1024]; //start time long begin = System.currenttimemillis (); //reads one byte array at a time (len = Inputstream.read (BS))!=-1) {Outputstream.write (Bs, 0, len); Span class= "hljs-comment" >//milliseconds System.out. println (System.currenttimemillis ()-begin); //281 inputstream. close (); OutputStream. close ();             
Read method Three:
FileInputStream InputStream =New FileInputStream ("f://skateboard//heel_flip.mp4"); Bufferedinputstream bis =New Bufferedinputstream (InputStream); FileOutputStream OutputStream =New FileOutputStream ( "Heel_flip.mp4"); Bufferedoutputstream BOS = new Bufferedoutputstream (outputstream); int len; byte[] bs = new byte[1024]; //start time long begin = System.currenttimemillis (); while (len = Bis.read (BS))!=-1) {Bos.write (Bs,len); } //time milliseconds System.out. println (System.currenttimemillis ()-begin); //bis. close (); Bos. close ();             

Note: It can be seen that the efficient buffer stream reading and writing speed is very fast, recommended.

More ways to view the API

Java Common IO Stream operation detailed

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.