Java FileInputStream read() Method
Example
Read a file one byte at a time:
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Hi");
myWriter.close();
FileInputStream input = new FileInputStream("filename.txt");
System.out.println((char) input.read());
System.out.println((char) input.read());
System.out.println(input.read());
input.close();
}
}
Definition and Usage
The read() method reads bytes (raw data) from the file.
Without arguments, it reads one byte and returns it as an int from 0 to 255. With a byte array, it reads many bytes into the array, and returns how many bytes it read. At the end of the file, it returns -1.
Tip: To print a byte from a text file as a character, cast (convert) it to char: (char) input.read().
Syntax
One of the following:
public int read()
public int read(byte[] b)
public int read(byte[] b, int off, int len)
Parameter Values
| Parameter | Description |
|---|---|
| b | Optional. A byte array to read the bytes into. |
| off | Optional. The index in the array where the first byte is put. |
| len | Optional. The largest number of bytes to read. |
Technical Details
| Returns: | The byte that was read (0 to 255), or the number of bytes that were read into the array. -1 at the end of the file. |
|---|---|
| Throws: | IOException - if the stream is closed, or if the file cannot be read. |
Related Pages
❮ FileInputStream Methods