java IO byte stream

Posted by RickyD77 on Mon, 24 Jan 2022 19:47:44 +0100

catalogue

IO stream overview and classification

concept

IO stream common parent class

IO stream program writing:

FileInputStream

Why is the return value of the read() method int instead of byte

FileOutputStream

copy picture

available() method of byte array copy

Define small arrays

Defines the standard format for small arrays

BufferedInputStream and BufferOutStream

The difference between flush and close methods

Byte stream reading and writing Chinese

Standard handling exceptions for streams

Image encryption

Copy file

Copy input data to file

 

IO stream overview and classification

concept

  • The IO stream is used to process data transmission between devices
  • Java operates on data through streaming z
  • Flow is divided into two types according to flow direction: input flow and output flow
  • Flows are divided into two types according to operation types
    • Byte stream: byte stream can manipulate any data, because any data is stored in bytes in the computer
    • Character class: character stream can only operate pure character data, which is more convenient

IO stream common parent class

Abstract parent class of byte stream

  • InputStream
  • OutputStream

Abstract parent class of character stream

  • Reader
  • Writer

IO stream program writing:

Before use: import the classes in the IO package

When in use: IO exception handling will be performed

After use: release resources

FileInputStream

Note: the blogger has created XXX under the current project Txt file is stored in abc

import javimport java.io.FileInputStream;
import java.io.IOException;

public class demo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("xxx.txt"); //Create flow object
        int x = fis.read();   //Read a byte from the hard disk
        System.out.println(x);

        int y = fis.read();
        System.out.println(y);

        int z = fis.read();
        System.out.println(z);

        int a = fis.read();
        System.out.println(a);
        fis.close();   //Close flow to release resources
    }
}

The output result is

It can be seen that when the program reads - 1, the file has been read, so the code can be modified as follows

import java.io.FileInputStream;
import java.io.IOException;

public class demo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("xxx.txt"); //Create flow object
        int b;
        while((b = fis.read()) != -1){
            System.out.println(b);
        }
        fis.close();   //Close flow to release resources
    }
}

Why is the return value of the read() method int instead of byte

Since the byte type operation uses the complement operation, the reading of 11111111 is the complement of - 1. Therefore, the reading of 11111111 will stop and the subsequent data will not be read. Therefore, when reading, it is received with int type. If 11111111 will add 24 zeros in front, the - 1 of byte type will become 255l of int type, so as to ensure the complete reading of the program

FileOutputStream

When creating an object, if there is no such file, create a file. If there is such a file, empty the contents of the file first

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

class demo2 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("yyy.txt");  //Create a byte output stream object. If not, create one yourself
        fos.write(97); //Although it is an int number written out, if it is a byte on the file, the first three 8 bits will be automatically removed
        fos.write(98);
        
        fos.close();
    }
}

The construction method of FileOutputStream writes out the data. How to realize the additional writing of data

 

import java.io.FileOutputStream;
import java.io.IOException;

public class demo4 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("yyy.txt",true); //If you want to continue writing, pass true in the second parameter
        fos.write(97);
    }
}

copy picture

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo5 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("i.JPG");
        FileOutputStream fos = new FileOutputStream("copy.jpg");

        int b ;
        while((b=fis.read()) != -1) {
            fos.write(b);
        }
        fis.close();
        fos.close();
    }
}

However, the efficiency of copying too large files is too slow, so it is not recommended in development

available() method of byte array copy

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo5 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("i.JPG");
        FileOutputStream fos = new FileOutputStream("copy.jpg");
//        int len = fis.available();
//        System.out.println(len);
        byte[] arr = new byte[fis.available()];  //Create an array of the same size as the file
        fis.read(arr);   //Reads the bytes on the file into memory 
        fos.write(arr);  //Write the byte data in the byte array to the file

        fis.close();
        fos.close();
    }
}

However, this method is not recommended in development because it may lead to memory overflow

Define small arrays

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo6 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("xxx.txt");
        FileOutputStream fos = new FileOutputStream("yyy.txt");
        byte[] arr = new byte[2];
        int len;     //len is the number of valid bytes read
        while((len = fis.read(arr)) != -1){
            fos.write(arr,0,len);
        }
        fis.close();
        fos.close();
    }
}

Defines the standard format for small arrays

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo6 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("xxx.txt");
        FileOutputStream fos = new FileOutputStream("yyy.txt");
        byte[] arr = new byte[1024 * 8];   //8k
        int len;     //len is the number of valid bytes read
        while((len = fis.read(arr)) != -1){  //If you forget to add arr, the number of bytes is not returned, but the code table value
            fos.write(arr,0,len);
        }
        fis.close();
        fos.close();
    }
}

BufferedInputStream and BufferOutStream

import java.io.*;

public class demo7 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("xxx.txt");  //Create an input stream object and associate XXX txt
        FileOutputStream fos = new FileOutputStream("yyy.txt"); //Create an output stream object and associate YYY txt
        BufferedInputStream bis = new BufferedInputStream(fis);  //Create a buffer object and wrap the input stream to make it more powerful
        BufferedOutputStream bos = new BufferedOutputStream(fos); //Create a buffer object and wrap the output stream to make it more powerful

        int b;
        while ((b = bis.read())!=-1) {
            bos.write(b);
        }
        bis.close();
        bos.close();
    }
}

schematic diagram

Buffer thought:

The speed of byte stream reading and writing one array at a time is much faster than that of reading one byte at a time

This is to add the buffer effect of array. java itself takes this design idea (decorative design mode) into account when designing, so it provides byte buffer stream

BufferedInputStream

BufferedInputStream has a built-in buffer array. When a byte is read from it, it will read 8192 from the file at one time. If it is stored in the buffer, it will be returned to the program. When the program reads again, it does not need to find the file. It will read directly from the buffer until all the bytes in the buffer have been used

BufferOutputStream

BufferOutputStream also has a built-in buffer array. When the program wants to write bytes in the stream, it will not write the file directly. It will write to the buffer first. It will not write the program to the file at one time until the buffer is full

Which is faster for small array reading and writing or Buffered reading

Define a small array. If the size of 8192 bytes is compared with Buffered, defining a small array will be slightly better, because the read and write operations are the same group of arrays, while Buffered operates on two arrays

The difference between flush and close methods

flush() method

The buffer used to refresh can be written out again after refresh

close() method

It is used to close the stream and release resources. If it is the close() method of the stream object with buffer, it will not only close the stream, but also refresh the buffer before closing the stream, refresh all the bytes of the buffer to the file, and cannot be written out after closing

Byte stream reading and writing Chinese

The problem of reading Chinese from byte stream

When the byte stream reads Chinese, it reads half of Chinese, which may be garbled

The problem of writing Chinese bytes

Byte stream directly operates on bytes, so to write Chinese, you must convert the string into a byte array

Write carriage return line feed write("\r\n".getBytes())

Standard handling exceptions for streams

JDK1.6 and previous treatment methods

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo6 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("xxx.txt");
            fos = new FileOutputStream("yyy.txt");
            byte[] arr = new byte[1024 * 8];   //8k
            int len;     //len is the number of valid bytes read
            while ((len = fis.read(arr)) != -1) {  //If you forget to add arr, the number of bytes is not returned, but the code table value
                fos.write(arr, 0, len);
            }
        }
        finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            }finally{                   //The purpose of nesting is to close one as much as possible
                if(fos != null) {
                    fos.close();
                 }
            }
        }
    }
}

JDK1.7. Treatment method

It will close itself after execution

import java.io.*;

public class demo7 {
    public static void main(String[] args) throws IOException {
        try(
            FileInputStream fis = new FileInputStream("xxx.txt");  //Create an input stream object and associate XXX txt
            FileOutputStream fos = new FileOutputStream("yyy.txt"); //Create an output stream object and associate YYY txt
        ){
            int b;
            while ((b = fis.read()) != -1) {
                fos.write(b);
            }
        }
    }
}

Image encryption

import java.io.*;

public class test {
    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("w.jpg"));
        BufferedOutputStream bos  = new BufferedOutputStream(new FileOutputStream("y.jpg"));
        int b;
        while((b = bis.read()) != -1) {
            bos.write(b ^ 123);
        }
        bis.close();
        bos.close();
    }
}

A number and the same number are XOR twice equal to itself

Copy file

import java.io.*;
import java.util.Scanner;

public class test2 {
    public static void main(String[] args) throws IOException {
        File file = getFile();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName()));     //Source file name
        int b;
        while((b=bis.read())!=-1) {
            bos.write(b);
        }
        bis.close();
        bos.close();

    }

    public static File getFile(){ //Judge whether the file path is a file before returning
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the file path:");

        while(true) {
            String s = sc.nextLine();
            File file = new File(s);
            if(!file.exists()) {
                System.out.println("The path you entered does not exist, please re-enter:");
            }else if(file.isDirectory()) {
                System.out.println("You have entered a folder path. Please re-enter:");
            }else {
                return file;
            }
        }
    }
}

Copy input data to file

mport java.io.FileOutputStream;
import java.io.IOException;

import java.util.Scanner;
public class test3 {
    public static void main(String[] args) throws IOException, IOException {
        Scanner sc = new Scanner(System.in);
        FileOutputStream fos = new FileOutputStream("test.txt");
        while(true){
            String s = sc.nextLine();
            if("quit".equals(s)){
                break;
            }
            fos.write(s.getBytes());
            fos.write("\r\n".getBytes());
        }
        fos.close();
    }
}

Topics: Java Back-end