java study notes: IO stream (input and output streams)

A, IO stream Summary and Classification
1 Overview: IO stream for processing data transfer between devices, Java operations on the data stream by way of, Java objects for the operation flow in the IO package
2, IO stream classification
according to the data flow

Input stream Output stream
Read data Write data

According to data types

Byte stream Character stream
You can read and write files of any type such as audio video text file You can read and write text files
Abstract base class byte stream: the InputStream, the OutputStream Abstract base class character streams: Reader, Writer
Byte input stream InputStream, byte output stream OutputStream Character-input stream Reader, character-output stream Writer

Note : This is derived from four abstract base class is a subclass name as a suffix to the name of its parent subclass name.
Second, the character stream
1, FileOutputStream write data

①, constructor
FileOutputStream (File file) // create a file for writing data file represented by the specified File object in the output stream.
FileOutputStream (String name) // create a writing data to a file with the specified name of the output file stream.
②, FileOutputStream three write () method
public void write (int b): a byte write more than one byte in front of the cut-byte
public void write (byte [] b ): Write a byte array
public void write (byte [] b, int off , int len): write a byte array part
③, FileOutputStream write data additional writing implement and linefeed

windows Linux Mac
\r\n \n \r

FileOutputStream (String name, boolean append) , parameter 2 representing whether additional writing
example: FileOutputStream out = new FileOutputStream ( " b.txt", true); // true represents additional writing

public class MyIODemo {
    public static void main(String[] args) throws IOException {
      //参2 代表是否追加写入
      //FileOutputStream(String name, boolean append)
      //创建一个向具有指定 name 的文件中写入数据的输出文件流。
      FileOutputStream out = new FileOutputStream("b.txt",true);//true 表示追加写入
      out.write(97); //一次写入一个字节
      out.write(98);
      //写入一个字节数组
      out.write("\r\n".getBytes());//换行
      out.write("像我这样优秀的人,本该灿烂过一生".getBytes());
      out.write("\r\n".getBytes());
      //写入字节数组的一部分 从某个索引开始,写多少个字节
      out.write("怎么二十多年到头来,还在人海里浮沉".getBytes(),0,27);
      out.write("\r\n".getBytes());
      //流使用完毕之后,必须释放资源
      out.close();
    }
}

3, FileInputStream read data
①, the input byte is obtained from the file system, a file
②, FileInputStream (String name)
connected to an actual file to be created by opening a FileInputStream, the file through the file system path name name specified.
③, FileInputStream (File file)
Creates a FileInputStream by opening a connection to the actual file, the file specified by the file system File object file.
④, file input stream, if there is no associated error is reported
int read (): read one byte, inefficient
byte [] bytes = new new byte [1024];
int len = in.read (bytes) ; // read once return value is an array of bytes that you read the byte number of valid
Note: after the stream after use, the resources must be released
4 byte input and output flow efficiency
BufferedOutputStream (OutputStream out) Create a new buffered output stream to write data to the specified underlying output stream.
BufferedInputStream (InputStream in) Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
Substantially the same efficient use of the input and output streams substantially byte stream
5, Case

分别使用使用高效字节流和基本字节流复制文件   
 public class MyDemo3 {
     public static void main(String[] args) throws IOException { 
        long start = System.currentTimeMillis();
        copy2(); //耗时18542毫秒  耗时13802毫秒
        copy1();  //耗时14046毫秒 耗时14331毫秒
        long end = System.currentTimeMillis();
        System.out.println("耗时"+(end-start)+"毫秒");
    }
    private static void copy2() throws IOException {
        FileInputStream in = new FileInputStream("E:\\我的图片和音乐\\疯狂动物城.mp4");
        FileOutputStream out = new FileOutputStream("D:\\疯狂动物城.mp4");
        //创建一个数组缓冲区
        byte[] bytes = new byte[1024*8];
        int len = 0; //记录读取到的有效的字节个数
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
            out.flush();
        }
        in.close();
        out.close();
    }
    private static void copy1() throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("E:\\我的图片和音乐\\疯狂动物城.mp4"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\疯狂动物城.mp4"));
        byte[] bytes = new byte[1024*8];
        int len=0;
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
        out.close();
        in.close();
    }
    }

Third, the character stream
1 because of character stream appears : Chinese operations due byte stream is not particularly convenient, therefore, java provides a character stream.
= + Byte stream character stream code table
2, String class coding and decoding problems in
coding : the string is converted into a byte array, the read can read into the

  • public byte [] getBytes (); using the platform's default character set encoding is byte String this sequence, storing the result into a new byte array.
  • public byte [] getBytes (String charsetName) using the specified character set coding this String is byte sequence, and storing the result into a new byte array.

Decoding : converting byte array into a string, into the read can understand

  • public String (byte [] bytes): Specifies default character set by using the internet decoded byte array, a new construct String.
  • public String (byte [] bytes, String charsetName) byte array specified by using the specified charset decoding, construct a new String.

3, the use of commutations OutputStreamWriter
①, OutputStreamWriter
is a bridge character streams to byte stream: the code table can be used to specify the character code written to the stream into bytes. It uses the character set can be specified by name or explicitly given, otherwise it will accept the platform's default character set.
②, the constructor
a: OutputStreamWriter (OutputStream out) // create the default character encoding OutputStreamWriter.
b: OutputStreamWriter (OutputStream out, Charset cs) // Creates a OutputStreamWriter given character set.
Note: The file associated with the output stream, and if not, the system will automatically create
③, 5 Zhong write characters the way data flows

public void write(int c) 写一个字符
public void write(char[] cbuf) 写一个字符数组
public void write(char[] cbuf,int off,int len) 写一个字符数组的 一部分
public void write(String str) 写一个字符串
public void write(String str,int off,int len) 写一个字符串的一部分
举例:
public class MyDemo {
public static void main(String[] args) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("a.txt"));
    //往文件中写入数据
    out.write('尼'); //一次写入一个字符
    out.write("\r\n");
    out.flush();
    out.write("我爱学java");
    out.write("\r\n");
    out.flush();
    out.write("路慢慢慢其修远兮,吾将上下而求索", 0, 8);
    out.write("\r\n");
    out.flush();
    out.write(new char[]{'a', '9', 98, 'e'});
    out.write("\r\n");
    out.write(new char[]{'我', '爱', '你', '们'}, 2, 2);
    out.write("\r\n");
    //字符流 需要将数据从缓冲区刷新过去
    out.flush();
    out.close(); //刷新并关闭
 }
}

4, the conversion using the stream InputStreamReader
① constructor
InputStreamReader (InputStream is): reading the default encoding (GBK) data
InputStreamReader (InputStream is, String charsetName) : read the data encoded with the specified
two kinds of read ②, the character stream form of the data
public int read () to read one character
public int read (char [] cbuf ) reads one character array or -1 if not read

  public class CopyFile2 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(new FileInputStream("a.txt"));
       OutputStreamWriter out = new OutputStreamWriter(newFileOutputStream("b.txt"));
        //创建一个字符缓冲区
        char[] chars = new char[100];  
        int len = 0; //len 是记录 你每次读取到的有效的字符个数
        while ((len=in.read(chars)) != -1) {
            out.write(chars, 0, len);//
            out.flush(); //字符流记得刷新一下
        }
        //释放资源
        in.close();
        out.close();
    }
}

5, convenient character stream classes
because the name is too long stream conversion, and we do not need to develop the character set in general, so java give us easy conversion corresponding to the stream class. The only drawback is that you can not specify the encoding.

Conversion flow Convenience class
OutputStreamWriter FileWriter
InputStreamReader FileReade

FileWriter (File File); Constructs a FileWriter object given a File object.
FileWriter (String fileName); configured FileWriter object given a file name.
6, a Book efficient character input stream
①, efficient character output stream: BufferedWriter // Write data
constructor: public BufferedWriter, (Writer W)
②, efficient character input stream: BufferedReader // data read
constructor: public BufferedReader (Reader e)
special function ③, character buffer stream
BufferedWriter: public void newLine (): the system determines the line break line feed system having compatibility.
BufferedReader: public String readLine (): once read a line of data is read newline newline is marked on the wrapping could read data returns null.

举例://使用高效的字符流,采用读取一行,写入一行的方式来复制文本文件
public class MyDemo8 {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("a.txt"));
        //BufferedWriter(Writer out)
        //创建一个使用默认大小输出缓冲区的缓冲字符输出流。
        BufferedWriter out = new BufferedWriter(new FileWriter("b.txt"));
        String line=null; //记录每次读取到的一行文本
        while ((line=in.readLine())!=null){ //这里注意读取不到返回null
            out.write(line);
            out.newLine(); //写入一个换行符
            out.flush();//刷新
        }
        //释放资源
        out.close();
        in.close();
    }
}
Published 24 original articles · won praise 11 · views 2051

Guess you like

Origin blog.csdn.net/weixin_43791069/article/details/86548116