×

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

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.