FileInputStream in Java

FileInputStream extends InputStream. A FileInputStream helps us to read the contents of a file as a stream of bytes.

Methods in FileInputStream

FileInputStream in Java

File Content to be read – abcdefgh12345678xyz.

package com.java.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileInpuutStreamExample {

    public static void main(String[] args) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("/Test/TestFolder/test-file.txt");
            System.out.println("File size (in bytes) : " + inputStream.available());
            int data = inputStream.read();
            while (data != -1) {
                data = inputStream.read();
                System.out.print((char) data);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

}
File size (in bytes) : 20
bcdefgh12345678xyz.

Related Article

Byte Stream Hierarchy in Java

Leave a Reply

Your email address will not be published. Required fields are marked *