In this article, we have discussed how to convert a java file to an InputStream. There is 5 very easy way to convert a java file to InputStream by Using Traditional java IO Package, using Java 8, Using Apache Common IO Library, Using Guava Library. Let’s look at some of the Java InputStream examples in this tutorial. Let’s convert a File to an InputStream in numerous ways of implementation. Before starting to convert a file to InputStream, let’s know what is an InputStream and 

What is InputStream?

InputStream is an abstract class of Java API.

Its a superclass of all classes defining an input stream of bytes.

InputStream extends Object and its implemented Interfaces are Closeable, AutoCloseable.

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

These are particularly helpful for reading and write operations on file streams or input files.

Again let’s go in detail about first, second, third ways of converting File to InputStream.

Convert using Traditional Java IO Package

Our first method to convert Java File To Inputstream.

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

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

Following Java code 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 output, the program reads a txt file and converts a File to an InputStream.

of course, next is by using SequenceInputStream.

Java program concatenates the 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 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]

These just for you,

File to InputStream using Java 8

Using Java 8 method to convert Java File To Inputstream.

Using Java 8, we can save the input stream to file as below

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

}

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

By using Apache Commons IO Library

Using Apache Commons IO Library API, we can convert java 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.

Java File to InputStream using Guava Library

It is my favorite, using Guava Library converts to inputstream in java.

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]

Read a File using InputStream in Java

file to input stream in java

java file to inputstream

There are numerous ways to read the contents of a file using Java InputStream.

Using BufferReader readLine() method

Read streams of raw bytes using Java InputStream and decode them into characters using charset.

Here readLine() method read bytes from the file and convert into characters.

This method will read the InputStream line by line in Java.

public static void main(String[] args) throws IOException {

	File file = new File("src/resources/hello.txt");
	String result = null;
	String line;	
	try {
	StringBuilder sb = new StringBuilder();
	InputStream in = new FileInputStream(file);
	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	while ((line = br.readLine()) != null) {
		sb.append(line + System.lineSeparator());
	}
		result = sb.toString();	
		br.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	System.out.println(result);
	}
}

Output:
Welcome

As the file “hello.txt” contains Welcome, it prints the same in the output above.

With Apache Commons IO package

Last but not the list to know how to convert file to an inputstream.

We can leverage the IOUtils class of Apache Commons IO library which will accept an InputStream

and displays the contents as a string using the specified content type.

The imports package for IOUtils is .apache.commons.io.IOUtils

public static void main(String[] args) throws IOException {

		File file = new File("src/resources/hello.txt");
		String results;
		try (InputStream in = new FileInputStream(file)) {
			results = IOUtils.toString(in, StandardCharsets.UTF_8);
			System.out.println(results);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Output:
Welcome

Using InputStream read() method

Last but not the list in file to inputstream,

Here read() method reads a byte data from the InputStream.

public static void main(String[] args) throws IOException {

		File file = new File("src/resources/hello.txt");
		int result;
		try (InputStream in = new FileInputStream(file)) {
			while ((result = in.read()) != -1) {
				System.out.print((char)result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Output:
Welcome

Tip:

Likewise, if you are looking to read a zip file, then use ZipInputStream to achieve it.

For reading large files like large CSV files, we can use Stream API from Java 8.

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

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

 

Interview FAQ

 

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();
}

What is ByteArrayInputStream?

ByteArrayInputStream will read byte array as input stream.

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

Also the ByteArrayInputStream buffer grows according to the data.

What is InputStreamReader?

InputStreamReader class translate bytes of an InputStream as text instead 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”).

InputStream inputStream = new FileInputStream(“sample.txt”);
InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName(“UTF-8”));

Also you can get the character encoding using method getEncoding().

FileInputStream fileStream = new FileInputStream(“sample.txt”);
InputStreamReader reader = new InputStreamReader(fileStream);
String encoding = reader.getEncoding();

Pin It on Pinterest

Share This