This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.

File byte stream

  • FileInputStream
  • FileOutputStream

It’s all for manipulating files. Read any file as bytes. An old friend will know at a glance, this last article is not sent, yes. This is how you read text files in the previous introductory article. Can poke: # Java file operation must know the concept review.

FileInputStream

Read a picture this time. Read the cover of this articleTopic. PNG:As a result, it did not exceed 255.

The main logic of the code is:

  1. Create an input stream object.
  2. newwhentry-catchAutomatic wrap with IDEA;
  3. And then manually addfinally(Must be addedfile.close());
  4. trywhen withwhileRead in a loopfile.read()The returnedThe int value.

FileOutputStream

  1. After reading, create a new output stream object.
  2. tryUnder the branch, while writes to the constructed output stream object (fos.write());
  3. whileOutside,flush()A;
  4. And don’t forget to be therefinallyNow close this object ~

In the code

package com.ftech.TestFileIO;

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

public class TestFileStream {
    public static void main(String[] args) {
        FileInputStream file = null;
        FileOutputStream fos = null;
        try {
            file = new FileInputStream("/ Users/fang/Images/subject. PNG");
            fos = new FileOutputStream("/ Users/fang/Images/title output. The PNG");
            int temp = 0;
            while((temp = file.read())! = -1){
                System.out.print(temp+"");
                fos.write(temp);
            }
            // Call from memory
            fos.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file! =null) {
                try {
                    file.close();
                } catch(IOException e) { e.printStackTrace(); }}try {
                fos.close();
            } catch(IOException e) { e.printStackTrace(); }}}}Copy the code

Operation effect:On the console side, it’s the same as before, just a bunch of ints.

Optimal point

The above is very inefficient to read while writing. Because it’s read and written byte by byte. The equivalent of shipping tens of thousands of beans, the method used in this paper is to accumulate a huge bag, rather than using similar small bags in batches. Let’s talk more next time.