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:

Spring 5 Testing with @EnabledIf Annotation
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to Implement Triply Linked List
Lớp Collections trong Java (Collections Utility Class)
Java Program to Implement Affine Cipher
Quick Guide to @RestClientTest in Spring Boot
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Java – Reader to String
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Changing Annotation Parameters At Runtime
ETL with Spring Cloud Data Flow
Reactive WebSockets with Spring 5
Java Program to Implement Bucket Sort
Java Program to Find the Edge Connectivity of a Graph
Programmatic Transaction Management in Spring
HandlerAdapters in Spring MVC
Java 14 Record Keyword
Guide to UUID in Java
Lớp LinkedHashMap trong Java
REST Web service: Upload và Download file với Jersey 2.x
Java Program to Generate N Number of Passwords of Length M Each
Java Program to Check whether Graph is a Bipartite using BFS
Spring Boot - Google OAuth2 Sign-In
RestTemplate Post Request with JSON
Giới thiệu Aspect Oriented Programming (AOP)
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Java Program to Implement Naor-Reingold Pseudo Random Function
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Java Program to Implement Insertion Sort
Creating Docker Images with Spring Boot