Read File in Java 10 Using FileInputStream

By | April 15, 2018

In this Java tutorial i’ll share about how to “Read File in Java 10 Using FileInputStream”. In Java, FileInputStream is a bytes stream class that’s used to read bytes from file. The following example will use FileInputStream to read a file named “C:/PromoTiketTraveloka.txt” and display its content to console. Before starting trying this example, please prepare the file before.

Read File in Java 10

See below for full example read file in java 10.

package com.cimblo.javacodeexample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author Cimblo
 * @since 15/04/2018
 */
public class ReadFileJava10FileInputStream {

    public static void main( String[] args ) throws FileNotFoundException{
        var readFile = new ReadFileJava10FileInputStream();
        //read file in java example 1
        readFile.readFileJavaExample1();
        //read file in java example 2, using new “try resource close” method to handle file easily.
        readFile.readFileJavaExample2();
    }

    private void readFileJavaExample1() throws FileNotFoundException{
        //first you must have this file to testing read file.
        var file = new File("C:/PromoTiketTraveloka.txt");
        var fis = new FileInputStream(file);

        try {

            System.out.println("Total file size to read (in bytes) : " + fis.available());

            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }

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

    private void readFileJavaExample2(){
        var file = new File("C:/PromoTiketTraveloka.txt");

        try (var fis = new FileInputStream(file)) {

            System.out.println("Total file size to read (in bytes) : "+ fis.available());

            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Do not forget to learn about “Write file in java 10” too.

References

  1. http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html

One thought on “Read File in Java 10 Using FileInputStream

  1. Pingback: Write to File in Java 10 Using FileOutputStream ~ Cimblo.com

Leave a Reply

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