×

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package.

Stream: A stream is nothing more than a data series. It is made up of bytes and is termed a stream because it resembles a flowing stream of water. All the streams are attached with console

  1. System.out : standard output stream
  2. System.in : standard input stream
  3. System.err: standard error steam

. File input stream is a part of input stream classes

. Let’s see a code to get input from the console

  • Int i = System.in.read(); // returns ASCII code for 1st character
  • System.out.println((char)i); //will print the character

FILE INPUT STREAM: An input stream is used by a Java programme to read data from a source, which might be a file or an array, for example. It holds an information byte from a record in the document framework. It is intended for reading raw data streams such as picture, video, and so on.

It is really preferable when using basic data type values. These are never compatible with ASCII characters.

The input stream class is abstract. The superclass of all classes address a byte input stream.

Java File Input Stream

File Inputstream Class Declaration:

Public class FileInputStream extends InputStream

Java Input Stream Class Methods

  • available(): it is utilized to return the assessed number of bytes that can be perused from the information
  • read(): its motivation is to peruse the byte of information from input stream
  • finalize(): Its motivation is to ensure that the shut technique is called when the document input stream is not generally referred to.
  • close(): Its motivation is to close the record. Program for simple input stream:
Import java.io.*;
Class FileInputStream // class name should be in camel case letters
{
Public static void main(String[] args)
{
  FileInputStream infile = null; //declaration
try {
infile = new FileInputStream(“a1.txt”); // initializing the text which I wanted to read
int b; // to store the output value
while(b=infile.read()!=-1) //here read method is invoked to read the data until the end of the file
{
System.out.println((char)b); //typecasting will be done here
}
Infile.close(); //closing of the file
} 
}

The above program is written to read the file which I want.

Constructors of file input stream class:

  1. FileInputStream(File file): generates a file stream input to read from the provided file object
  2. FileInputStream(FileDescriptor fdobj): generates an input file stream from the provided file descriptor
  3. FileInputStream(String name): generates an input file stream to read from the provided file.

When we employ these approaches, we often follow the procedures below. To read data from a file using FileInputStream, we often follow these steps, which is the end aim of the file input class.

Step1:  Attach a file to FileInputStream so that we may read data from it.

 fileInputStream = new FileInputStream(“file.txt”);

Step2: to read the file the syntax is

Ch = fileInputStream.read();

Step3: When there is no more data to be read, the read() function returns -1.

The monitor should then be connected to the output stream. We may use System.out.print to display the data.
              System.out.print(ch);

. FileInputStream extends the InputStream abstract class

//program for file input stream

import java.io.FileInputStream.*;
 public class Head
 public static void main (String args[]) {
try {
new FileInputStream("input.txt") input = new FileInputStream("input.txt");
System.out.println("File data: ");
// Retrieves the first byte
input.read(); int I = input.read();
while (i!= -1)
System.out.print((char)i);
// Gets the next byte from the file.
input = read();
}
input.close();
}
catching(Exception e)
e.getStackTrace();
}
}
}

We also utilise the available() function in this FileInputStream to get the number of available bytes in the file input stream. The skip() function can be used to discard and skip the provided number of bytes.

A file reader is a kind of InputStreamReader that can only read from files and utilises the platform's default encoding.  As such, it expects that the record being perused was created as per your working framework's foundation encoding settings, subsequently you ought to fabricate a FileInputStream and enclose it by an InputStreamReader.

Advantages:

It is intended for reading raw bytes streams such as picture data. It also indicates a byte ordering mechanism. We can read data in the form of an ordered series of bytes. The operator >> is used.

Disadvantages:

Regardless of whether you close a FileInputStream fittingly, it will be put in a unique classification that might be tidied up when the garbage man does a full GC. Due to in reverse similarity impediments, we can't resolve issue in the JDK.

Key Points:

  • The classes under byte stream are input stream and result stream; they are not streams.
  • Record peruse is utilized to peruse the documents
  • peruse() technique for File Reader class is utilized to understand characters
  • CharArrayReader is an execution of an info stream
  • there are 7 sub classes of information stream classes
  • Byte stream are arranged into 2 class order they are input stream and result stream
  • FilterInputStream and SequenceInputStream are the sub classes of InputStream

//let’s see another program to know more about file input stream

// Java Program to Demonstrate FileInputStream Class

import java.io.*;
class Java {
// Main method
public static void main(String args[])
throws IOException
{


// Attaching the file to FileInputStream
FileInputStream f1 = new FileInputStream("f1.txt");
                       // Invoking  getChannel() method
System.out.println(f1.getChannel());
                       // Invoking getFD() method
System.out.println(fin.getFD());
                        // Illustrating available method
System.out.println("Number of remaining bytes:"+ fin.available());
                        // Illustrating skip() method
fin.skip(4);
                       // Display message for better readability
System.out.println("FileContents :");
                        int ch;
                         while ((ch = fin.read()) != -1)
System.out.print((char)ch);


// Close the 
           F1.close();
}
}

Syntax for declaring the methods in file input stream:

 public int read() throws IOException
 public int read(byte[] b)throws IOException
 public int read(byte[] b, int offset, intlen) throws IOException
 public int available() throws IOException
 public FileChannelgetChannel()
 protected void finalize() throws IOException
 public final FileDescriptorgetFD() throws IOException
 public void close() throws IOException

These are the declaring syntax for file input streams in java application.


Related Topics

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.