Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream?

前端 未结 3 1233
挽巷
挽巷 2020-11-28 19:49

I was trying to read a file into an array by using FileInputStream, and an ~800KB file took about 3 seconds to read into memory. I then tried the same code except with the F

3条回答
  •  -上瘾入骨i
    2020-11-28 20:16

    It is because of the cost of disk access. Lets assume you will have a file which size is 8kb. 8*1024 times access disk will be needed to read this file without BufferedInputStream.

    At this point, BufferedStream comes to the scene and acts as a middle man between FileInputStream and the file to be read.

    In one shot, will get chunks of bytes default is 8kb to memory and then FileInputStream will read bytes from this middle man. This will decrease the time of the operation.

    private void exercise1WithBufferedStream() {
          long start= System.currentTimeMillis();
            try (FileInputStream myFile = new FileInputStream("anyFile.txt")) {
                BufferedInputStream bufferedInputStream = new BufferedInputStream(myFile);
                boolean eof = false;
                while (!eof) {
                    int inByteValue = bufferedInputStream.read();
                    if (inByteValue == -1) eof = true;
                }
            } catch (IOException e) {
                System.out.println("Could not read the stream...");
                e.printStackTrace();
            }
            System.out.println("time passed with buffered:" + (System.currentTimeMillis()-start));
        }
    
    
        private void exercise1() {
            long start= System.currentTimeMillis();
            try (FileInputStream myFile = new FileInputStream("anyFile.txt")) {
                boolean eof = false;
                while (!eof) {
                    int inByteValue = myFile.read();
                    if (inByteValue == -1) eof = true;
                }
            } catch (IOException e) {
                System.out.println("Could not read the stream...");
                e.printStackTrace();
            }
            System.out.println("time passed without buffered:" + (System.currentTimeMillis()-start));
        }
    

提交回复
热议问题