Java – Convert File to InputStream

1. Overview

In this quick tutorial, we’re going to show how to convert a File to an InputStream – first using plain Java and then Guava and the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

2. Convert Using Java

We can use the IO package of java to convert a File to different InputStreams.

2.1. FileInputStream

Let’s start with the first and simplest one – using a FileInputStream:

@Test
public void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() 
  throws IOException {
    File initialFile = new File("src/main/resources/sample.txt");
    InputStream targetStream = new FileInputStream(initialFile);
}

2.2. DataInputStream

Let’s look at another one, where we can use DataInputStream to read binary or primitive data from a file:

@Test
public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() 
  throws IOException {
      final File initialFile = new File("src/test/resources/sample.txt");
      final InputStream targetStream = 
        new DataInputStream(new FileInputStream(initialFile));
}

2.3. SequenceInputStream

Finally, let’s also look at how to use SequenceInputStream to concatenate input stream of two files to a single InputStream:

@Test
public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() 
  throws IOException {
      final File initialFile = new File("src/test/resources/sample.txt");
      final File anotherFile = new File("src/test/resources/anothersample.txt");
      final InputStream targetStream = new FileInputStream(initialFile);
      final InputStream anotherTargetStream = new FileInputStream(anotherFile);
    
      InputStream sequenceTargetStream = 
        new SequenceInputStream(targetStream, anotherTargetStream);
}

Note that we’re not closing the resulting stream in these examples for legibility.

3. Convert Using Guava

Next – let’s see the Guava solution, using an intermediary ByteSource:

@Test
public void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() 
  throws IOException {
    File initialFile = new File("src/main/resources/sample.txt");
    InputStream targetStream = Files.asByteSource(initialFile).openStream();
}

4. Convert Using Commons IO

Finally – let’s look at a solution using Apache Commons IO:

@Test
public void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() 
  throws IOException {
    File initialFile = new File("src/main/resources/sample.txt");
    InputStream targetStream = FileUtils.openInputStream(initialFile);
}

And there you have it – 3 simple and clean solutions for opening a stream from a Java file.

5. Conclusion

In this article, we explored various ways on how to convert a File to InputStream by using different libraries.
The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.

Related posts:

Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Implement Park-Miller Random Number Generation Algorithm
Interface trong Java 8 – Default method và Static method
Spring Boot Integration Testing with Embedded MongoDB
A Guide To UDP In Java
Java Program to Implement Fermat Factorization Algorithm
Ép kiểu trong Java (Type casting)
Java Program to Check the Connectivity of Graph Using DFS
Marker Interface trong Java
Java Program to Implement Queue
Java Program to Check Multiplicability of Two Matrices
@Order in Spring
Spring Boot - Tomcat Deployment
Exploring the Spring 5 WebFlux URL Matching
File Upload with Spring MVC
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Giới thiệu luồng vào ra (I/O) trong Java
Java Program to Implement Iterative Deepening
Spring 5 WebClient
Java Program to Implement Skew Heap
Getting the Size of an Iterable in Java
Java Program to Implement Shunting Yard Algorithm
Java Program to Perform Stooge Sort
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Uploading MultipartFile with Spring RestTemplate
Java Program to Emulate N Dice Roller
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Spring Boot - Introduction
Java Program to Find Inverse of a Matrix
Generate Spring Boot REST Client with Swagger