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.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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

1. Introduction

In this tutorial, we’ll cover Java IO functionalities and how they changed throughout different Java versions. First, we’ll cover the java.io package from the initial Java version. Next, we’ll go over java.nio package introduced in Java 1.4. In the end, we’ll cover the java.nio.file package, commonly known as the NIO.2 package.

2. Java NIO Package

The first Java version was released with the java.io package, introducing a File class to access the file system. The File class represents files and directories and provides limited operations on the file system. It was possible to create and delete files, check if they exist, check read/write access, etc.

It also has some shortcomings:

  • Lack of copy method – to copy a file, we need to create two File instances and use a buffer to read from one and write to another File instance.
  • Bad error handling  – some methods return boolean as an indicator if an operation is successful or not.
  • A limited set of file attributes – name, path, read/write privileges, memory size is available, to name a few.
  • Blocking API – our thread is blocked until the IO operation is complete.

To read a file, we need a FileInputStream instance to read bytes from the file:

@Test
public void readFromFileUsingFileIO() throws Exception {
    File file = new File("src/test/resources/nio-vs-nio2.txt");
    FileInputStream in = new FileInputStream(file);
    StringBuilder content = new StringBuilder();
    int data = in.read();
    while (data != -1) {
        content.append((char) data);
        data = in.read();
    }
    in.close();
    assertThat(content.toString()).isEqualTo("Hello from file!");
}

Next, Java 1.4 introduces non-blocking IO API bundled in java.nio package (nio stands for new IO). NIO was introduced to overcome the limitations of the java.io package. This package introduced three core classes: Channel, Buffer, and Selector.

2.1. Channel

Java NIO Channel is a class that allows us to read and write to a buffer. Channel class is similar to Streams (here we speak of IO Streams, not Java 1.8 Streams) with a couple of differences. Channel is a two-way street while Streams are usually one-way, and they can read and write asynchronously.

There are couple implementations of the Channel class, including FileChannel for file system read/write, DatagramChannel for read/write over a network using UDP, and SocketChannel for read/write over a network using TCP.

2.2. Buffer

Buffer is a block of memory from which we can read or write data into it. NIO Buffer object wraps a memory block. Buffer class provides a set of functionalities to work with the memory block. To work with Buffer objects, we need to understand three major properties of the Buffer class: capacity, position, and limit.

  • Capacity defines the size of the memory block. When we write data to the buffer, we can write only a limited length. When the buffer is full, we need to read the data or clear it.
  • The position is the starting point where we write our data. An empty buffer starts from 0 and goes to capacity – 1. Also, when we read the data, we start from the position value.
  • Limit means how we can write and read from the buffer.

There are multiple variations of the Buffer class. One for each primitive Java type, excluding the Boolean type plus the MappedByteBuffer.

To work with a buffer, we need to know a few important methods:

  • allocate(int value) – we use this method to create a buffer of a certain size.
  • flip() – this method is used to switch from write to read mode
  • clear() – method for clearing the content of the buffer
  • compact() – method for clearing only the content we have already read
  • rewind() – resets position back to 0 so we can reread the data in the buffer

Using previously described concepts, let’s use Channel and Buffer classes to read content from file:

@Test
public void readFromFileUsingFileChannel() throws Exception {
    RandomAccessFile file = new RandomAccessFile("src/test/resources/nio-vs-nio2.txt", "r");
    FileChannel channel = file.getChannel();
    StringBuilder content = new StringBuilder();
    ByteBuffer buffer = ByteBuffer.allocate(256);
    int bytesRead = channel.read(buffer);
    while (bytesRead != -1) {
        buffer.flip();
        while (buffer.hasRemaining()) {
            content.append((char) buffer.get());
        }
        buffer.clear();
        bytesRead = channel.read(buffer);
    }
    file.close();
    assertThat(content.toString()).isEqualTo("Hello from file!");
}

After initializing all required objects, we read from the channel into the buffer. Next, in the while loop, we mark the buffer for reading using the flip() method and read one byte at a time, and append it to our result. In the end, we clear the data and read another batch.

2.3. Selector

Java NIO Selector allows us to manage multiple channels with a single thread. To use a selector object to monitor multiple channels, each channel instance must be in the non-blocking mode, and we must register it. After channel registration, we get a SelectionKey object representing the connection between channel and selector. When we have multiple channels connected to a selector, we can use the select() method to check how many channels are ready for use. After calling the select() method, we can use selectedKeys() method to fetch all ready channels.

2.4. Shortcomings of NIO Package

The changes java.nio package introduced is more related to low-level data IO. While they allowed non-blocking API, other aspects remained problematic:

  • Limited support for symbolic links
  • Limited support for file attributes access
  • Missing better file system management tools

3. Java NIO.2 Package

Java 1.7 introduces new java.nio.file package, also known as NIO.2 package. This package follows an asynchronous approach to non-blocking IO not supported in java.nio package. The most significant changes are related to high-level file manipulation. They are added with Files, Path, and Paths classes. The most notable low-level change is the addition of AsynchroniousFileChannel and AsyncroniousSocketChannel.

Path object represents a hierarchical sequence of directories and file names separated by a delimiter. The root component is furthest to the left, while the file is right. This class provides utility methods such as getFileName(), getParent(), etc. The Path class also provides resolve and relativize methods that help construct paths between different files. Paths class is a set of static utility methods that receive String or URI to create Path instances.

Files class provides utility methods that use the previously described Path class and operate on files, directories, and symbolic links. It also provides a way to read many file attributes using readAttributes() method.

In the end, let’s see how NIO.2 compares to previous IO versions when it comes to reading a file:

@Test
public void readFromFileUsingNIO2() throws Exception {
    List<String> strings = Files.readAllLines(Paths.get("src/test/resources/nio-vs-nio2.txt"));
    assertThat(strings.get(0)).isEqualTo("Hello from file!");
}

4. Conclusion

In this article, we covered the basics of java.nio and java.nio.file packages. As we can see, NIO.2 is not the new version of the NIO package. The NIO package introduced a low-level API for non-blocking IO, while NIO.2 introduced better file management. These two packages are not synonymous, rather a compliment to each other.

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.

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