Java FileInputsStream Class |Methods And Examples

Java FileInputsStream Class is used for reading a file, like a Text file, Audio, video etc. The Java.io.FileInputStream class obtains input bytes from a file in the form of a sequence of bytes.

A java.io.InputStream is a parent class of FileInputStream Class. When coming to reading a file, there is a way to read the file. Its depend on what kind of file for rading.

  • Raw bytes – For image data.
  • Characters – For reading streams of characters, use FileReader.

Class declaration

Java FileInputsStream example

Let’s see the example and how to use a FileInputStream. Below Image is shows project structure of where is a file located for reading data from it and what content is inside the text file. Text file name is – ” text.txt”

Java FileInputsStream example

Example: How to Read single character with Java FileInputsStream

For that, you need to import a Java.io.FileInputStream then create an object for FileInputStream with the file name or complete file path name. Use the read() method for reading text from the file with a file input stream. Using typecasting convert byte to char, otherwise, the output will print a byte.

Note: don’t forget to add file with some content, otherwise program will throw an error.

Output: F

Example: Read all Content from File using Java FileInputStream

Same as the above example but that time using While Loop to print all characters from file.

Output: FilesInputStream Example

Java FileInputStream class methods

MethodDescription
int available()A return the estimated number of bytes remaining (that can be read) from the input stream.
int read()Reads a byte of data from this input stream.
int read(byte[] b)Read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int len)Read up to len bytes of data from the input stream.
long skip(long x)Skip over and discards x bytes of data from the input stream.
FileChannel getChannel()Return the unique FileChannel object associated with the file input stream.
FileDescriptor getFD()Return the FileDescriptor object.
protected void finalize()A method used for ensures that the close method of this file. In input stream is called when there are no more references to it.
void close()The closes file input stream and release system resources which associated with the stream.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All  Java FileInputsStream Class examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.