Looking to convert Java InputStream from File? In this tutorial, lets have a look at how to convert a File to an InputStream.

What is InputStream?

InputStream is an abstract class in Java api.

It is the super class of all classes defining an input stream of bytes.

InputStream can extend Object and implemented Interfaces are Closeable, AutoCloseable.

InputStream Subclasses are AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream.

These are particularly help for read and write operations on file stream or input file.

Again lets go in details about first, second, third ways of converting File to InputStream.

Convert using Traditional Java IO Package

In the first place, lets leverage Java IO package to convert a File format to different InputStream’s.

Of course under IO package, first one we use is FileInputStream.

The following java code will read a file from the file path/folder directory location.

Furthermore it converts into InputStream using method FileInputStream().

public static void main(String[] args) throws IOException {
	try {
		File file = new File("src/resources/hello.txt");
		InputStream is = new FileInputStream(file);
		System.out.println("InputStream is: " + is);
        is.close();
	} catch (Exception e) {
			e.printStackTrace();
	}
}

Output:
InputStream is: [email protected]

As per the above output, the program can also read a txt file and converts a File to an InputStream.

Next is by using SequenceInputStream.

Below Java program will concatenates input data stream of two files to a single InputStream.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	File file2 = new File("src/resources/Test.txt");
	InputStream firstIS = new FileInputStream(file);
	InputStream secondIS = new FileInputStream(file2);
	InputStream is = new SequenceInputStream(firstIS, secondIS);
	System.out.println("SequenceInputStream is: "+is);
    firstIS.close();
	secondIS.close();
	is.close();
    } catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
SequenceInputStream is: [email protected]



Not to mention, finally using by DataInputStream.

This will read primitive data stream or binary data from a file.

public static void main(String[] args) throws IOException {
try {
	 File file = new File("src/resources/Hello.txt");
 	 InputStream is = new DataInputStream(new FileInputStream(file));
  	 System.out.println("DataInputStream is: "+is);	
     is.close();
	 } catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
DataInputStream is: [email protected]

Using Java 8

Using Java 8, we can save inputstream to file as below

public static void main(String[] args) throws IOException {
		String TARGET_PATH = "C:\\test\\wikipedia.txt";
	try {
		URI u = URI.create("https://www.wikipedia.com/");
		InputStream inputStream = u.toURL().openStream();
		Files.copy(inputStream, Paths.get(TARGET_PATH),StandardCopyOption.REPLACE_EXISTING);
		System.out.println("File is copied to location: " + TARGET_PATH);
	} catch (Exception e) {
		e.printStackTrace();
	}

}

Output:
File is copied to location: C:\test\wikipedia.txt

By using Apache Commons IO Library

Using Apache Commons IO Library api, we can convert File to an InputStream as below.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	InputStream is = FileUtils.openInputStream(file);
	System.out.println("Apache Commons InputStream is: "+is);		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
Apache Commons InputStream is: [email protected]

Apache Commons IO library can be download from here.

Convert using Guava Library:

As we know Guava is an open source Java api library from Google.

Using Guava we can convert File to an InputStream with below source code.

public static void main(String[] args) throws IOException {
try {
	File file = new File("src/resources/Hello.txt");
	InputStream is = Files.asByteSource(file).openStream();
	System.out.println("Guava Google InputStream is: "+is);		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output:
Guava Google InputStream is: [email protected]



Tip: Likewise, if you are looking to read an zip file, then use ZipInputStream is to achieve it.

Interview Questions:

1. What is Scanner class?

Java Scanner is used to read user input and it part of java.util package.

2. How to read InputStream line by line in Java?

We can use BufferedReader with FileInputStreamReader to read InputStream line by line.

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
while(bufferReader.ready()) {
     String line = bufferReader.readLine();
}

3. What is ByteArrayInputStream?

ByteArrayInputStream is used to read byte array as input stream.

This class consists an internal buffer which is used to read the byte array as a stream.

Also the ByteArrayInputStream buffer grows automatically according to the data.

3. What is InputStreamReader?

InputStreamReader class is used to translate the bytes of an InputStream as text in place of numeric data.

Also we can set and get the character encoding using InputStreamReader.

You can set the character encoding using method Charset.forName(“UTF-8”) as below

InputStream inputStream = new FileInputStream("sample.txt");

InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));

You can get the character encoding using method getEncoding() as below

FileInputStream fileStream = new FileInputStream("sample.txt");

InputStreamReader reader = new InputStreamReader(fileStream);

String encoding = reader.getEncoding();


For reading a large files like largeCSV file, we can use Stream API from Java 8.

Also for parsing a CSV file, we can use Apache commons CSV libray and BufferedReader.

To conclude this java tutorial, we covered various examples using different packages/libraries.

Pin It on Pinterest

Share This