How to Convert InputStream to DataHandler in Java
Working with large files in Java can lead to memory issues when using InputStream directly. This guide explains how to convert an InputStream to a DataHandler efficiently, avoiding OutOfMemoryError exceptions while maintaining performance.
Why InputStream Alone Fails for Large Files
When you use resultSet.getBytes() to load an entire file into memory, it works for small files but causes severe problems for large datasets. For example:
byte[] bytes = resultSet.getBytes(1);
DataHandler dh = new DataHandler(bytes, "application/octet-stream");This approach loads the entire file into a byte array, exhausting heap space and leading to crashes. Memory inefficiency becomes a critical bottleneck.
Solution: Use getBinaryStream and DataSource
The getBinaryStream() method retrieves data as an InputStream, avoiding full memory allocation. However, DataHandler requires a DataSource implementation to work with streams. Here’s how to implement it:
Step 1: Create a Custom DataSource
Implement the DataSource interface to wrap your InputStream:
public class StreamDataSource implements DataSource {
private final InputStream inputStream;
public StreamDataSource(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public InputStream getInputStream() throws IOException {
return inputStream;
}
@Override
public OutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException("Not supported");
}
@Override
public String getContentType() {
return "application/octet-stream";
}
@Override
public String getName() {
return "StreamDataSource";
}
}Step 2: Convert to DataHandler
Use the custom DataSource to create a DataHandler:
InputStream inputStream = resultSet.getBinaryStream(1);
DataSource dataSource = new StreamDataSource(inputStream);
DataHandler dataHandler = new DataHandler(dataSource);Key Benefits of This Approach
- Processes large files without loading them entirely into memory
- Prevents
OutOfMemoryErrorexceptions - Compatible with Java Activation Framework (JAF)
Common Pitfalls to Avoid
1. Don’t close the InputStream prematurely: Ensure the stream remains open until the DataHandler finishes processing.
2. Use try-with-resources carefully: If you close the stream too early, subsequent operations on the DataHandler will fail.
Conclusion
By implementing a custom DataSource, you can convert an InputStream to a DataHandler efficiently. This method is ideal for handling large files in Java applications while maintaining memory safety.
Call to Action
Ready to optimize your Java file handling? Implement this solution today to avoid memory issues in your applications.








