Implement how to load File as InputStream in Java
Last Updated :
21 Sep, 2021
Problem Statement: There is a file already existing in which the same file needs to be loaded using the InputStream method.
Concept: While accessing a file either the file is being read or write. here are two streams namely fileInputStream and fileOutputStream
Java Stream is the flow of data from source to destination. OutputStream and InputStream are abstractions over low-level access to data. InputStream is a source for reading data. A stream can have various kinds of sources, such as disk files, devices, other programs, and memory arrays. Several ways to read the contents of a file using InputStream in Java have been discussed below.
Suppose the text file is stored in path "/Users/mayanksolanki/Desktop/Folder/test.txt” and has content as below:
Approaches:
- Using Apache command IO libraries
- Using readline() method of BufferedReaderClass
- Using read() method of InputStreamClass
Let us describe and implement the methods one by one through examples:
Method 1: Using Apache Common IO library
The IOUtils class from Apache Commons IO library contains a toString() method that accepts an InputStream and renders its contents as a string as shown below:
Java
// Importing generic Classes/Files
import java.util.*;
// importing Apache specific Class/es
import org.apache.commons.io.IOUtils;
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating file object and specify file path
File file = new file(
"/Users/mayanksolanki/Desktop/Folder/test.txt");
// create a stream to read contents of that file
// Try block to check exception
try {
FileInputStream input
= new FileInputStream(file);
// Representing input object in form of string
String contents = IOUtils.toString(input);
// Print contents of that file
System.out.println(contents);
}
// Catch block to handle exceptions
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Method 2: BufferedReader’s readLine() method
Concept Used: Using inbuilt readLine() function : The readLine() method of BufferedReader class in Java is used to read one line text at a time. The end of a line is to be understood by ‘\r’ or ‘\n’ or EOF.
Here is the implementation of readLine() method:
Java
// Importing generic Classes/Files
import java.io.*;
class GFG {
// Main driver method
public static void main(String[] args)
{
// Create file object and specify file path
File file = new File(
"/Users/mayanksolanki/Desktop/Folder/test.txt");
try (FileInputStream input
= new FileInputStream(file)) {
// create an empty string builder to store
// string
StringBuilder content = new StringBuilder();
// create an object of bufferedReader to read
// lines from file
BufferedReader br = new BufferedReader(
new InputStreamReader(input));
String line;
// store each line one by one until reach end of
// file
while ((line = br.readLine()) != null) {
// append string builder with line and with
// '/n' or '/r' or EOF
content.append(line
+ System.lineSeparator());
}
// print string builder object i.e content
System.out.println(content.toString());
}
// Catch block to handle exceptions
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Method 3: InputStream’s read() method
The read() method of InputStream class, reads a byte of data from the input stream. The next byte of data is returned, or -1 if the end of the file is reached and throws an exception if an I/O error occurs. Refer to the program.
Java
// Importing generic Classes/Files
import java.io.*;
class GFG {
// Main driver function
public static void main(String[] args)
{
// Creating file object and specifying path
File file = new File(
"/Users/mayanksolanki/Desktop/Folder/test.txt");
try (FileInputStream input
= new FileInputStream(file)) {
int character;
// read character by character
// by default read() function return int between
// 0 and 255.
while ((character = input.read()) != -1) {
System.out.print((char)character);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
There is another overloaded version of read() method that reads the specified length of bytes from the input stream into an array of bytes. The corresponding bytes can then be decoded into characters. Refer to the below example.
Java
import java.nio.charset.StandardCharsets;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// create file object and specify path
// specicified directory is random
File file = new File(
"/Users/mayanksolanki/Desktop/Folder/test.txt");
// Try block to catch exception/s if any
try {
(FileInputStream input
= new FileInputStream(file))
// create a byte array of size equal to
// length of file
byte bytes[]
= new byte[(int)file.length()];
// read bytes from file
input.read(bytes);
// decode into string format
String content
= new String(bytes, StandardCharsets.UTF_8);
// print contents of that file
System.out.println(content);
}
catch (Exception e) {
//
e.printStackTrace();
}
}
}
Output
The output of all the above programs is the same.
Similar Reads
How to Convert InputStream to Byte Array in Java?
In Java, input stream refers to an ordered flow of data in the form of bytes. This flow of data can be coming from various resources such as files, network programs, input devices, etc. In order to read such data, we have a Java InputStream Class in the Java IO API. There are several methods to conv
5 min read
How to Lock a File in Java?
In Java, file locking involves stopping processes or threads from changing a file. It comes in handy for threaded applications that require simultaneous access, to a file or to safeguard a file from modifications while it's being used by our application. When reading or writing files we need to make
2 min read
How to Implement File Locking in Java to Prevent Concurrent Access ?
In Java, Concurrent file access may cause corruption and errors in the data. File locking is used to stop many threads or processes from concurrently accessing the same file. A simple method for implementing file locking in Java is the FileLock class, which comes under java.nio.channels package. The
2 min read
Difference Between InputStream and OutputStream in Java
A stream can be defined as the sequence of data or continuous flow of data. Streams are a clear way to deal with Input/Output. Streams are of two types as Depicted below: In the above diagram, our InputStream and OutputStream will reside in Byte Stream. So let's discuss byte Stream. 1. Byte Stream:
4 min read
How to List all Files in a Directory in Java?
Java provides a feature to interact with the file system through the java.io.file package. This feature helps developers automate the things to operate with files and directories. In this article, we will learn how to list all the files in a directory in Java. Approaches to list all files in a direc
3 min read
How to Check if a File Exists in Java?
In Java programming, working with files is now a more common task. Developing a code to manage file automatization using Java. In this article, we will discuss how to check if a file exists in Java. By using the java.io.File class we will discuss two methods to check if a file exists or not. Approac
3 min read
How to Read and Write JSON Files in Java?
JSON (JavaScript Object Notation) is simple but poweÂrful.. It helps the server and the client to share information. Applications like Java use special tools, or libraries, that reÂad JSON. In Java, some libraries make it easy to read and write JSON files. One popular library is Jackson.In this art
4 min read
Java Program to Convert InputStream to String
Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read
4 min read
Java Program to Convert String to InputStream
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations. Illustration: Input : String : "Geeks for Geeks" Output : Input Stream : Geeks for Geeks Input : String : "A computer science portal" Output : Input stream : A computer science portal In order
2 min read
How to Read and Write XML Files in Java?
XML is defined as the Extensible Markup Language, and it is mostly used as a format for storing and exchanging data between systems. To read and write XML files, Java programming offers several easily implementable libraries. The most widely used library is the built-in JAXP (Java API for XML proces
5 min read