Does Java's try-catch-resources flush automatically?


When using an object of type FileInputStream and FileOutputStream inside a try-catch-resources, java automatically uses close() at the end, but is flush() automatic or not?

// Exemplo
try(FileOutputStream fos = new FileOutputStream("arquivo.txt")){
    try (BufferedOutputStream bos = new BufferedOutputStream(fos)) {
        bos.flush(); // Precisa usar o flush()
    fos.flush(); // Precisa usar o flush()


Whether or not flush is automatic depends on the implementation of the concrete class you use.

The try with resources only expects Closeable or AutoCloseable objects, it is not linked directly to the flush, however some implementations of these interfaces perform the flush before the close.

Scroll to Top