Dark Horse Programmer _java Basics _ My Day20 study notes

Source: Internet
Author: User
Tags closing tag

IO Stream (key knowledge) 01. IO Flow overview 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
    • 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();                                            //关闭流释放资源
The. Read () method returns a value of what is an int???
    • The Read () method reads a byte, why it is returned as an int, not a byte

    • Because the byte input stream can manipulate any type of file, such as chip audio, these files are stored in binary form, if each read is returned byte, it is possible to read in the middle of the time encountered 111111111
      Then this 11111111 is a byte type of-1, our program is encountered-1 will stop the unread, the back of the data is not read, so at the time of reading with the int type received, if 11111111 will be in front of it to fill
      24 0 To make up 4 bytes, then 1 of the byte type becomes 255 of the int type so that the entire data is read, and the -1 of the closing tag is the int type
    • Write () write one byte at a time

    • FileOutputStream fos = new FileOutputStream ("Bbb.txt"); If there is no bbb.txt, it creates a
      Fos.write (97); Although the write is an int number, but in the written time will be the first 24 0 removed, so write a byte
      Fos.write (98);
      Fos.write (99);
      Fos.close ();
FileOutputStream Append
    • A: Case Demo
      • FileOutputStream Construction method writes out how data is implemented to append data

    • FileOutputStream fos = new FileOutputStream ("Bbb.txt", true); If there is no bbb.txt, it creates a
      Fos.write (97); Although the write is an int number, but in the written time will be the first 24 0 removed, so write a byte
      Fos.write (98);
      Fos.write (99);
      Fos.close ();
06. Copy Pictures
    • 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();
07. Copy audio file drawing schematic (deprecated)
    • A: Case Demo
      • A byte stream reads and writes one bytes of copy audio
    • Disadvantages: Too low efficiency
08. Byte array copy of the available () method (not recommended this way, disadvantages)
    • 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();
09. Defining Decimal Groups
    • Write (byte[] b)
    • Write (byte[] b, int off, int len) write a valid number of bytes
10. Define a standard format for decimal groups
    • A: Case Demo

      • Byte stream reads and writes a single array of bytes 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 the byte array to write out the number of valid bytes

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

Bufferedinputstream and Bufferoutputstream copies
  • 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.
Differences between the 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. Byte stream reading and writing 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. Flow Standard handling Exception code version 1.6 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. Flow Standard handling Exception code 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. 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. Copying files
    • 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. Copy data 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();

Dark Horse Programmer _java Basics _ My Day20 study notes

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.