The Java API already contains a method that seems very convenient for you. InputStream
defines the following method.
public abstract int read() throws IOException;
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
It should make it trivial to read integers from a file one byte at a time (assuming characters to integers is one-to-one; int
is actually four bytes in size).
An example of using this method to read characters individually as int
and then casting to char
follows. Again, this assumes that each character is encoded as a single byte, and that there is a one-to-one from characters to int
s. If you're dealing with multi-byte character encoding and/or you want to support integers greater than 255, then the problem becomes more complex.
public static void main(String[] args) {
ByteArrayInputStream in = new ByteArrayInputStream("abc".getBytes());
int value;
while ((value = in.read()) > -1) {
System.out.println((char) value);
}
}