eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

File handling is an essential aspect we frequently encounter. When it comes to writing data to files, the FileWriter class is commonly used. Within this class, two important methods, flush() and close(), play distinct roles in managing file output streams.

In this tutorial, we’ll address FileWriter‘s common usage and delve into the differences between its flush() and close() methods.

2. FileWriter and try-with-resources

The try-with-resources statement in Java is a powerful mechanism for managing resources, especially when dealing with I/O operations such as file handling. It automatically closes the resources specified in its declaration once the code block is exited, whether normally or due to an exception.

However, there might be situations where using FileWriter with try-with-resources is not ideal or necessary.

FileWriter may behave differently with or without try-with-resources. Next, let’s take a closer look at it.

2.1. Using FileWriter With try-with-resources

If we use FileWriter with try-with-resources, the FileWriter object gets flushed and closed automatically when we exit the try-with-resources block.

Next, let’s show this in a unit test:

@Test
void whenUsingFileWriterWithTryWithResources_thenAutoClosed(@TempDir Path tmpDir) throws IOException {
    Path filePath = tmpDir.resolve("auto-close.txt");
    File file = filePath.toFile();

    try (FileWriter fw = new FileWriter(file)) {
        fw.write("Catch Me If You Can");
    }

    List<String> lines = Files.readAllLines(filePath);
    assertEquals(List.of("Catch Me If You Can"), lines);
}

Since our test will write and read files, we employed JUnit5’s temporary directory extension (@TempDir). With this extension, we can concentrate on testing the core logic without manually creating and managing temporary directories and files for testing purposes.

As the test method shows, we write a string in the try-with-resources block. Then, when we check the file content using Files.readAllLines()we get the expected result.

2.2. Using FileWriter Without try-with-resources

However, when we use FileWriter without try-with-resources, the FileWriter object won’t automatically get flushed and closed:

@Test
void whenUsingFileWriterWithoutFlush_thenDataWontBeWritten(@TempDir Path tmpDir) throws IOException {
    Path filePath = tmpDir.resolve("noFlush.txt");
    File file = filePath.toFile();
    FileWriter fw = new FileWriter(file);
    fw.write("Catch Me If You Can");

    List<String> lines = Files.readAllLines(filePath);
    assertEquals(0, lines.size());
    fw.close(); //close the resource
}

As the test above shows, although we wrote some text to the file by calling FileWriter.write(), the file was still empty.

Next, let’s figure out how to solve this problem.

3. FileWriter.flush() and FileWriter.close()

In this section, let’s first solve the “file is still empty” problem. Then, we’ll discuss the difference between FileWriter.flush() and FileWriter.close().

3.1. Solving “The File Is Still Empty” Problem

First, let’s understand quickly why the file is still empty after we called FileWriter.write(). 

When we invoke FileWriter.write(), the data is not immediately written to the file on the disk. Instead, it is temporarily stored in a buffer. Consequently, to visualize the data in the file, it is necessary to flush the buffered data to the file.

The straightforward way is to call the flush() method:

@Test
void whenUsingFileWriterWithFlush_thenGetExpectedResult(@TempDir Path tmpDir) throws IOException {
    Path filePath = tmpDir.resolve("flush1.txt");
    File file = filePath.toFile();
    
    FileWriter fw = new FileWriter(file);
    fw.write("Catch Me If You Can");
    fw.flush();

    List<String> lines = Files.readAllLines(filePath);
    assertEquals(List.of("Catch Me If You Can"), lines);
    fw.close(); //close the resource
}

As we can see, after calling flush(), we can obtain the expected data by reading the file.

Alternatively, we can call the close() method to transfer the buffered data to the file. This is because close() first performs flush, then closes the file stream writer.

Next, let’s create a test to verify this:

@Test
void whenUsingFileWriterWithClose_thenGetExpectedResult(@TempDir Path tmpDir) throws IOException {
    Path filePath = tmpDir.resolve("close1.txt");
    File file = filePath.toFile();
    FileWriter fw = new FileWriter(file);
    fw.write("Catch Me If You Can");
    fw.close();

    List<String> lines = Files.readAllLines(filePath);
    assertEquals(List.of("Catch Me If You Can"), lines);
}

So, it looks pretty similar to the flush() call. However, the two methods serve different purposes when handling file output streams.

Next, let’s have a close look at their differences.

3.2. The Difference Between the flush() and close() Methods

The flush() method is primarily used to force any buffered data to be written immediately without closing the FileWriter, while the close() method both performs flushing and releases associated resources.

In other words, invoking flush() ensures that the buffered data is promptly written to disk, allowing continued write or append operations to the file without closing the stream. Conversely, when close() is called, it writes the existing buffered data to the file and then closes it. Consequently, further data cannot be written to the file unless a new stream is opened, such as by initializing a new FileWriter object.

Next, let’s understand this through some examples:

@Test
void whenUsingFileWriterWithFlushMultiTimes_thenGetExpectedResult(@TempDir Path tmpDir) throws IOException {
    List<String> lines = List.of("Catch Me If You Can", "A Man Called Otto", "Saving Private Ryan");
    Path filePath = tmpDir.resolve("flush2.txt");
    File file = filePath.toFile();
    FileWriter fw = new FileWriter(file);
    for (String line : lines) {
        fw.write(line + System.lineSeparator());
        fw.flush();
    }

    List<String> linesInFile = Files.readAllLines(filePath);
    assertEquals(lines, linesInFile);
    fw.close(); //close the resource
}

In the above example, we called write() three times to write three lines to the file. After each write() call, we invoked flush(). In the end, we can read the three lines from the target file.

However, if we attempt to write data after calling FileWriter.close(), IOException with the error message “Stream closed” will raise:

@Test
void whenUsingFileWriterWithCloseMultiTimes_thenGetIOExpectedException(@TempDir Path tmpDir) throws IOException {
    List<String> lines = List.of("Catch Me If You Can", "A Man Called Otto", "Saving Private Ryan");
    Path filePath = tmpDir.resolve("close2.txt");
    File file = filePath.toFile();
    FileWriter fw = new FileWriter(file);
    //write and close
    fw.write(lines.get(0) + System.lineSeparator());
    fw.close();

    //writing again throws IOException
    Throwable throwable = assertThrows(IOException.class, () -> fw.write(lines.get(1)));
    assertEquals("Stream closed", throwable.getMessage());
}

4. Conclusion

In this article, we explored FileWriter‘s common usage. Also, we discussed the difference between FileWriter‘s flush() and close() methods.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)