<

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

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 Baeldung.

Further reading:

Java Scanner

Tutorial and examples on Java Scanner - scan a String, a File or the Console, validate the input, find or skip Patterns.

Read more

Guava – Write to File, Read from File

How to Write to File and Read from a File using the Guava IO support and utilities.

Read more

Java Byte Array to InputStream

How to convert a byte[] to an InputStream using plain Java or Guava.

Read more

2. Convert using Java

Let’s start with the simple Java solution – 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);
}

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

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.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

  Subscribe  
newest oldest most voted
Notify of
алексей боев
Guest
алексей боев

thanks. nice design )

Java Developer
Guest

Thanks it works on my mac somehow the File for current directory does not work on windows.

Grzegorz Piwowarek
Guest
Grzegorz Piwowarek

Hi, can you give more details?