Java has Two types of streams- Byte & Characters. For reading and writing binary data, byte stream is incorporated. The InputStream abstract class is used to read data from a file. The FileInputStream is the subclass of the InputStream abstract class. The FileInputStream is used to read data from a file.
The read() method of an InputStream returns an int which contains the byte value of the byte read. If there is no more data left in stream to read, the read() method returns -1 and it can be closed after this. One thing to note here, the value -1 is an int not a byte value.
Given below example will give you a clear idea :
The content in the Devfile.txt :
The text shown here will write to a file after run
FileInStreamDemo.java
import java.io.*;
public class FileInStreamDemo {
public static void main(String[] args) {
// create file object
File file = new File("DevFile.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (FileNotFoundException e) {
System.out.println("File " + file.getAbsolutePath()
+ " could not be found on filesystem");
} catch (IOException ioe) {
System.out.println("Exception while reading the file" + ioe);
}
System.out.println("File contents :");
System.out.println(strContent);
}
}
The command prompt will show you the following data :
| File contents :
The text shown here will write to a file after run |
|
Recommend the tutorial |

Ask Questions? Discuss: Java FileInputStream Example
Post your Comment