FileInputStream
is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using
Java FileReader.
FileInputStream Constructors:
FileInputStream Methods:
Example Program:
/* This is the content of file : MeritCampus.txt
This is an example for FileInputStream.
*/
import java.io.FileInputStream;
import java.io.File;
import java.awt.BorderLayout;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
File file = new File("MeritCampus.txt");
try (FileInputStream fis1 = new FileInputStream(file)) {
//display available bytes
System.out.println("Total file size to read (in bytes) : "+ fis1.available());
//skip bytes from file input stream
fis1.skip(5);
int content;
while ((content = fis1.read()) != -1) {
//to convert into char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
Image image=null;
try (FileInputStream fis2 = new FileInputStream("image.jpg")) {
image = ImageIO.read(fis2);
} catch (IOException e) {
e.printStackTrace();
}
//to display the image read
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Output:
Total file size to read (in bytes) : 39
is an example for FileInputStream.
//the following image is displayed in a window
Description:
The input bytes of the file
MeritCampus.txt
is obtained by the
FileInputStream
and the total size of the file is displayed. Five bytes of the file is skipped and the remaining content is read and printed. The second
FileInputStream
obtains an image and it is displayed with the help of Java Swing in a window. Note that the full path is to be given if the file or image is not located in the same folder as the
java
file on the system and this is a JDK7 example, where the new “try resource close” method to handle the file easily is used.
Things to try:
- Try to read the data into an array using
read(byte[] b)
method instead of just reading data and printing them.
- Try to read the data into an array starting at the offset using
read(byte[] b, int off, int len)
method instead of just reading data and printing them.
- Try displaying different images in different formats by obtaining input bytes using
FileInputStream
.