Java- Streams with buffered

So recently i have learned to work with streams, both with input and output to learn so i can read from a file and write to one. But my teacher sometimes decides to use buffered and sometimes he does not. Like in this case ill post the code. Do you guys understand why he has not put an bufferedoutputstream in this case?

  public void writePrimes2(String filename) throws IOException {
        try(ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename))){
            os.writeObject(primes);
            os.flush();
        }
    }

Answer

BufferedOutputStream and FileOutputStream both work similarly. Internally BufferedOutputStream writes to a internal buffer and not directly to the Operating System IO device and when the buffer is full or closed, it flushes the contents of the buffer to the OS IO device. This can be more efficient/faster on some OS. But the result is that the output can appear slightly delayed because of buffering.

Leave a Reply

Your email address will not be published. Required fields are marked *