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

Last time, the common Java stream object, file byte stream (cache), tried two ways to cache using byte[] arrays to improve read and write efficiency. Here’s how to use a byte cache stream to copy images:

Core code explanation

The process is the same: IO stream instantiate — read — write — flush — close the stream.

  • Instantiate an empty file object, and then pass in the new one as a wholeBufferedInputStreamBufferedOutputStreamGo in;

  • inwhileThe read() method of the cache stream object;
  • whileIn the loop, as long as you don’t get to the end, keep tuning.write();
  • At the end of the loop, refresh once.flush();
  • Close the stream in turn.

Close the details

  • About processing flow and node flow

A cache flow is a processing flow, and a processing flow is a layer of flow wrapped around a node flow. So when you close, you close the processing stream first, and then you close the first onefisFlow. If you write it, put itfisfosThe correspondingnew FileInputSteamandnew FileOutputStreamWhen closed, only the processing stream is closed, and the node stream is also closed: for bos example, source tracing is performed on.close() : Through hereoutYou can jump toOutputSteamHere:It is true that the input stream is also closed.

  • About input and output streams:

If you look at it from an input-output point of view, you have an output before an input, so you have to close the output stream before you close the input stream.

code

static void bufferedFS(a) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            fis = new FileInputStream("/ Users/fang/Images/subject. PNG");
            bis = new BufferedInputStream(fis);
            fos = new FileOutputStream("Output4 / Users/fang/Images/subject. PNG");
            bos = new BufferedOutputStream(fos);
            int temp = 0;
            while((temp = bis.read())! = -1) {
                bos.write(temp);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            try { // Open before close
                bos.close();
                bis.close();
                fos.close();
                fis.close();
                
// if (bis! =null) {
// bis.close();
/ /}
// if (fis! =null) {
// fis.close();
/ /}
// if (bos! =null) {
// bos.close();
/ /}
// if (fos! =null) {
// fos.close();
/ /}

            } catch(IOException e) { e.printStackTrace(); }}}Copy the code

The results

It can be found that there is little difference in efficiency between the two usages above.