Java FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Java FileInputStream class declaration
Let's see the declaration for java.io.FileInputStream class:
- public class FileInputStream extends InputStream
Java FileInputStream example 1: read single character
- import java.io.FileInputStream;
- public class DataStreamExample {
- public static void main(String args[]){
- try{
- FileInputStream fin=new FileInputStream("testout.txt");
- int i=fin.read();
- System.out.print((char)i);
-
- fin.close();
- }catch(Exception e){System.out.println(e);}
- }
- }
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content:
After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character.
Output:
Java FileInputStream example 2: read all characters
-
-
- import java.io.FileInputStream;
- public class DataStreamExample {
- public static void main(String args[]){
- try{
- FileInputStream fin=new FileInputStream("testout.txt");
- int i=0;
- while((i=fin.read())!=-1){
- System.out.print((char)i);
- }
- fin.close();
- }catch(Exception e){System.out.println(e);}
- }
- }
Sign up here with your email
ConversionConversion EmoticonEmoticon