Java EE Basics (20)/io stream

Source: Internet
Author: User

1. Io Stream (Overview of IO Stream and its classification)
    • 1. Concept
      • IO streams are used to process data transfer between devices
      • The Java operation of the data is streamed through the way
      • The classes that Java uses to manipulate the flow are in the IO package
      • Flows are divided into two types: input stream, output stream.
      • There are two types of flows by operation type:
        • BYTE stream: A byte stream can manipulate any data, because any data in the computer is stored in bytes
        • Character Stream: Character stream can only manipulate pure character data, it is more convenient.
    • 2.IO Stream Common Parent class
      • Abstract parent class for byte stream:
        • InputStream
        • OutputStream
      • Abstract parent class for character streams:
        • Reader
        • Writer
    • 3.IO Program Writing
      • Before using, import the classes in the IO package
      • IO exception handling when used
      • After use, release resources
2. Io Stream (FileInputStream)
    • Read () reads one byte at a time
    • FileInputStream fis = new FileInputStream("aaa.txt");   //创建一个文件输入流对象,并关联aaa.txtint b;                                                  //定义变量,记录每次读到的字节while((b = fis.read()) != -1) {                         //将每次读到的字节赋值给b并判断是否是-1    System.out.println(b);                              //打印每一个字节}fis.close();                                            //关闭流释放资源
3. IO Stream (The Read () method returns a value of what is int)
    • The Read () method reads a byte, why it is returned as an int, not a byte
    • 因为字节输入流可以操作任意类型的文件,比片音频等,这些文件底层都是以二进制形式的存储的,如果每次读取都返回byte,有可能在读到中间的时候遇到111111111那么这11111111是byte类型的-1,我们的程序是遇到-1就会停止不读了,后面的数据就读不到了,所以在读取的时候用int类型接收,如果11111111会在其前面补上24个0凑足4个字节,那么byte类型的-1就变成int类型的255了这样可以保证整个数据读完,而结束标记的-1就是int类型
4. Io Stream (FileOutputStream)
    • Write () write one byte at a time
    • FileOutputStream fos = new FileOutputStream("bbb.txt"); //如果没有bbb.txt,会创建出一个//fos.write(97);                        //虽然写出的是一个int数,但是在写出的时候会将前面的24个0去掉,所以写出的一个bytefos.write(98);fos.write(99);fos.close();
5. Io Stream (fileoutputstream append)
    • A: Case Demo
      • FileOutputStream Construction method writes out how data is implemented to append data
    • FileOutputStream fos = new FileOutputStream("bbb.txt",true);    //如果没有bbb.txt,会创建出一个//fos.write(97);                        //虽然写出的是一个int数,但是在写出的时候会将前面的24个0去掉,所以写出的一个bytefos.write(98);fos.write(99);fos.close();
6. Io stream (copy picture)
    • FileInputStream Read
    • FileOutputStream Write

      FileInputStream fis = new FileInputStream("致青春.mp3");   //创建输入流对象,关联致青春.mp3FileOutputStream fos = new FileOutputStream("copy.mp3");//创建输出流对象,关联copy.mp3int b;while((b = fis.read()) != -1) {    fos.write(b);}fis.close();fos.close();
7. Io Stream (copy audio file drawing schematic)
    • A: Case Demo
      • A byte stream reads and writes one bytes of copy audio
    • Disadvantages: Too low efficiency
8. Io Stream (available () method of byte array copy)
    • A: Case Demo
      • int read (byte[] b): reads one byte array at a time
      • Write (byte[] b): Writes out one byte array at a time
      • Available () Gets the number of bytes of the read file
    • Cons: There may be memory overflow

      FileInputStream fis = new FileInputStream("致青春.mp3");FileOutputStream fos = new FileOutputStream("copy.mp3");byte[] arr = new byte[fis.available()];                 //根据文件大小做一个字节数组fis.read(arr);                                          //将文件上的所有字节读取到数组中fos.write(arr);                                         //将数组中的所有字节一次写到了文件上fis.close();fos.close();
9. Io Stream (define decimal group)
    • Write (byte[] b)
    • Write (byte[] b, int off, int len) write a valid number of bytes
10. Io Stream (defines the standard format for decimal groups)
    • A: Case Demo

      • Byte stream reads and writes a bytes array copy pictures and videos FileInputStream fis = new FileInputStream ("to Youth. mp3"); FileOutputStream fos = new FileOutputStream ("Copy.mp3"); int Len; byte[] arr = new byte[1024 * 8]; Custom byte array

        while (len = Fis.read (arr))! =-1) {//fos.write (arr); Fos.write (arr, 0, Len);//write out byte array write valid number of bytes}

        Fis.close (); Fos.close ();

11. Io Stream (Bufferedinputstream and bufferoutputstream copy)
  • A: The idea of buffering
    • Byte stream the speed of reading and writing an array is significantly faster than reading and writing one byte at a time,
    • This is a buffer effect added to the array, Java itself at the time of design,
    • It also takes into account the idea of design (which is explained later in the decorative design pattern), so it provides a byte buffer stream
  • B.bufferedinputstream
    • Bufferedinputstream has a buffer (array) built into it
    • When reading a byte from the Bufferedinputstream
    • Bufferedinputstream will read from the file 8,192 at a time, there is a buffer, return to the program a
    • When the program reads again, it doesn't have to find the file, it gets it directly from the buffer.
    • Until all of the buffers have been used, only 8,192 are read back from the file
  • C.bufferedoutputstream
    • Bufferedoutputstream also has a built-in buffer (array)
    • When the program writes out bytes to the stream, it is not written directly to the file, written to the buffer
    • Until the buffer is full, Bufferedoutputstream writes the data in the buffer once to the file.
  • D. Copy the Code

    FileInputStream fis = new FileInputStream("致青春.mp3");           //创建文件输入流对象,关联致青春.mp3BufferedInputStream bis = new BufferedInputStream(fis);         //创建缓冲区对fis装饰FileOutputStream fos = new FileOutputStream("copy.mp3");        //创建输出流对象,关联copy.mp3BufferedOutputStream bos = new BufferedOutputStream(fos);       //创建缓冲区对fos装饰int b;while((b = bis.read()) != -1) {         bos.write(b);}bis.close();                        //只关装饰后的对象即可bos.close();
  • E. Read and write of decimal groups and reading with buffered which is faster?

    • Define a decimal group if it is a 8,192-byte size and a buffered comparison.
    • Defining decimal groups is notch above because the same array of read and write operations
    • And buffered is manipulating two arrays.
12. Io Stream (difference between flush and close methods)
    • Flush () method
      • Used to flush the buffer, which can be written again after the refresh.
    • Close () method
      • The close () method of the Stream object that is used to shut down the stream frees the stream, not only closes the flow, but also flushes the buffer before closing the stream, and can no longer write
13, Io Stream (byte stream read and write Chinese)
    • The problem of reading Chinese by byte stream
      • Byte stream when reading Chinese, it is possible to read half of Chinese, resulting in garbled characters
    • Word Stream Write Chinese question
      • Byte stream is directly manipulated, so writing Chinese must convert the string to a byte array
      • Write a carriage return newline write ("\ r \ n". GetBytes ());
14. IO Stream (Standard handling exception code version 1.6 of the stream and its previous)
    • Try finally nesting

      FileInputStream fis = null;FileOutputStream fos = null;try {    fis = new FileInputStream("aaa.txt");    fos = new FileOutputStream("bbb.txt");    int b;    while((b = fis.read()) != -1) {        fos.write(b);    }} finally {    try {        if(fis != null)            fis.close();    }finally {        if(fos != null)            fos.close();    }}
15. IO Stream (standard handling exception code for stream 1.7 version)
    • Try Close

      try(    FileInputStream fis = new FileInputStream("aaa.txt");    FileOutputStream fos = new FileOutputStream("bbb.txt");    MyClose mc = new MyClose();){    int b;    while((b = fis.read()) != -1) {        fos.write(b);    }}
    • Principle
      • The stream object created in try () must implement the Autocloseable interface, which, if implemented, is automatically called after the {} (read-write code) is executed after the try, and the Close method of the stream object turns the stream off
16. IO Stream (Image encryption)
    • Encrypt pictures

      BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.jpg"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.jpg"));int b;while((b = bis.read()) != -1) {    bos.write(b ^ 123);}bis.close();bos.close();
17. Io Stream (copy file)
    • Enter the path to the file in the console and copy the file to the current project

      Scanner sc = new Scanner(System.in);System.out.println("请输入一个文件路径");String line = sc.nextLine();                //将键盘录入的文件路径存储在line中File file = new File(line);                 //封装成File对象FileInputStream fis = new FileInputStream(file);FileOutputStream fos = new FileOutputStream(file.getName());int len;byte[] arr = new byte[8192];                //定义缓冲区while((len = fis.read(arr)) != -1) {    fos.write(arr,0,len);}fis.close();fos.close();
18, IO Stream (input data copy to file)
    • Copy the keyboard input data into the Text.txt file under the current project, and the keyboard input data will exit when it encounters quit.

      Scanner sc = new Scanner(System.in);FileOutputStream fos = new FileOutputStream("text.txt");System.out.println("请输入:");while(true) {    String line = sc.nextLine();    if("quit".equals(line))        break;    fos.write(line.getBytes());    fos.write("\r\n".getBytes());}fos.close();

Java EE Basics (20)/io stream

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.