Convert a String into the InputStream in Java

Exercise:

Write a Java Program to convert a string into the input stream.

Click Here to View the Solution!
import java.io.InputStream;
import java.io.FileInputStream;

public class Main {
    public static void main(String args[]) {
        try {

            // file input.txt is loaded as input stream
            // input.txt file contains:
            // This is a content of the file input.txt
            InputStream input = new FileInputStream("input.txt");
            System.out.println("Data in the file: ");

            // Reads the first byte
            int i = input.read();
            while(i != -1) {
                System.out.print((char)i);

            // Reads next byte from the file
              i = input.read();
            }
            input.close();
        }
        catch(Exception e) {
            e.getStackTrace();
        }
    }
}
Click Here to View the Output!
 Data in the file: 
 This is a content of the file input.txt.
Click Here to View the Explanation!
  • This program depicts the usage of FileInputStream class for the purpose of loading the contents of a file as an input stream.
  • First step to load the input stream is to instantiate an object of FileInputStream class.
  • Instantiation process includes, passing a file name to the constructor.
  • Then move on to storing these bytes of input into an object of InputStream class type.
  • Before displaying the contents of the file, we have to make sure that the file isn’t empty.
  • Therefore, first byte of the file is checked, if it tends to be equal to negative 1 then the file is empty.
  • Otherwise, the loop continues and the bytes of contents are read one by.
  • Once the contents are displayed, file is closed.

%d bloggers like this: