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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

When working with large files in Java, developers may encounter memory restrictions while reading from an input stream. In particular, the challenge of converting an InputStream to a DataHandler while maintaining memory efficiency is a common problem.

In this tutorial, we’ll cover how to convert an InputStream to a DataHandler. First, we’ll understand why memory inefficiency occurs when extracting the content from large files using InputStream. Next, we’ll cover the getBinaryStream function and its limitations. After that, we’ll elaborate on the working of a DataHandler. Lastly, we’ll implement the DataSource and its implementation.

2. Understanding the InputStream Problem

When working with files, a common technique is to extract the entire file content as a byte array using the getBytes() method on a ResultSet object when retrieving the data from the databases. Moreover, this byte array gets converted into a DataHandler using the constructor that accepts a byte array and a MIME type specification.

Let’s look at the sample code:

byte[] bytes = resultSet.getBytes(1);
   DataHandler dh = new DataHandler(bytes, "application/octet-stream");

While this approach works for small files, it becomes problematic when dealing with larger files. To elaborate, the entire file content must reside in memory simultaneously. As a result, applications may experience OutOfMemoryError exceptions or severe performance degradation as heap space becomes exhausted.

3. Using getBinaryStream

The first solution to overcome the problem we described uses getBinaryStream to retrieve data as an InputStream. Through this approach, we have access to the content without loading everything into memory at once. However, the DataHandler class doesn’t provide a direct constructor that accepts an InputStream. This creates a barrier to implementation.

Furthermore, attempts to create an empty DataHandler that provides access to an OutputStream prove unsuccessful because the DataHandler method getOutputStream typically returns null unless the underlying data source explicitly supports output operations.

4. Working of a DataHandler

The Java Activation Framework doesn’t provide a constructor that accepts an InputStream directly when creating a DataHandler. That’s where DataSource comes in. DataHandler works with DataSource objects and serves as an abstraction layer that encapsulates data and provides methods for accessing both input and output streams.

It is important to note that since Java 11, the Java Activation Framework, javax.activation is no longer included in the JDK. Therefore, we must explicitly add the required dependency to our project.

4.1. Implementing the DataSource

For this example, we create a custom class that implements the DataSource interface. This class provides four essential methods:

  • getInputStream()
  • getOutputStream()
  • getContentType()
  • getName()

Let’s look at the code of InputStreamDataSource.java:

public class InputStreamDataSource implements DataSource {
    private InputStream inputStream;
    public InputStreamDataSource(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    @Override
    public InputStream getInputStream() throws IOException {
        return inputStream;
    }
    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }
    @Override
    public String getContentType() {
        return "*/*";
    }
    @Override
    public String getName() {
        return "InputStreamDataSource";
    }
}

In this case, we only implemented getInputStream to demonstrate the function. The getOutputStream method throws an UnsupportedOperationException because the use case we present only requires reading data, not writing it.

4.2. DataSource Usage

Now we use the reusable InputStreamDataSource to create a DataHandler. The following example simulates retrieving data from a database. We simulate retrieving data from a database and creating a DataHandler in DataSourceDemo.java:

public class DataSourceDemo {
    public static void main(String[] args) {
        try {
            String sampleData = "Hello from the database! This could be a large file.";
            InputStream inputStream = new ByteArrayInputStream(sampleData.getBytes());
            
            System.out.println("Step 1: Retrieved InputStream from database");
            System.out.println("Data size: " + sampleData.length() + " bytes\n");
            
            DataHandler dataHandler = new DataHandler(
                new InputStreamDataSource(inputStream)
            );
            
            System.out.println("Step 2: Created DataHandler successfully!");
            System.out.println("Content type: " + dataHandler.getContentType());
            System.out.println("Data source name: " + dataHandler.getName() + "\n");
            
            InputStream resultStream = dataHandler.getInputStream();
            String retrievedData = new String(resultStream.readAllBytes());
            
            System.out.println("Step 3: Retrieved data from DataHandler:");
            System.out.println("\"" + retrievedData + "\"");
            System.out.println("\n✓ Success! Data streamed without loading entirely into memory first.");
            
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

In the above example, we wrap the InputStream in our InputStreamDataSource and then create a DataHandler. Although readAllBytes() simplifies the example, it loads the entire content into memory. This defeats the purpose of streaming for large files. In real-world applications, we process the InputStream incrementally using buffered reads to preserve memory efficiency.

Next, we compile the file:

javac DataSourceDemo.java
java DataSourceDemo

The output now displays the streamed data:

Step 1: Retrieved InputStream from database
Data size: 52 bytes
Step 2: Created DataHandler successfully!
Content type: */*
Data source name: InputStreamDataSource
Step 3: Retrieved data from DataHandler:
"Hello from the database! This could be a large file."
✓ Success! Data streamed without loading entirely into memory first.

Critically, we replace the simulation code with the real database code in the actual environment.

The key advantage of this approach is that the data remains in the database and streams through the application as needed. The memory footprint stays constant regardless of file size, which enables the application to handle files that would previously cause memory exhaustion.

4.3. Using Content Type

While the basic implementation works well for read-only scenarios, some situations may require additional functionality. For instance, if the content type needs to be specified dynamically rather than using a wildcard, the InputStreamDataSource constructor can be enhanced to accept a MIME type parameter:

public class EnhancedDataSourceDemo {
    public static void main(String[] args) {
        try {
            ...
            InputStream pdfStream = new ByteArrayInputStream("PDF content here".getBytes());
            DataHandler pdfHandler = new DataHandler(
                new InputStreamDataSource(pdfStream, "application/pdf")
            );
            System.out.println("Content type: " + pdfHandler.getContentType());
            System.out.println();
        }
...
    }
}

Through this modification, we enable precise content type specification modification. This is useful specifically where the MIME type affects behavior, such as email attachments or HTTP responses.

5. Conclusion

In this article, we covered how to convert an InputStream to a DataHandler. First, we explained the memory efficiency problem in Java. After that, we covered the inefficiency of using getBytes alone. Lastly, we discussed converting an InputStream to a DataHandler using the DataSource abstraction.

The source code is available over on GitHub.

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)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments