Reading bytes of data
From http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html
http://www.cafeaulait.org/course/week10/06.html
The basic read()
method of the InputStream
class reads a single unsigned byte of data and returns the int
value of the unsigned byte. This is a number between 0 and 255. If the end of stream is encountered, it returns -1 instead; and you can use this as a flag to watch for the end of stream.
public abstract int read() throws IOException
Here's a simple program that echoes back what the user types at the command line. The byte is cast to its equivalent in the ISO Latin-1 character set before being printed. This program does not properly handle Unicode. In general, input and output streams do not properly handle Unicode data. Therefore you should use them only for raw data and use the java.io.Reader
and java.io.Writer
classes for text data, especially non-ASCII data.
/* Note that as a general rule on most platforms characters
are only sent to System.in a line at a time, not as each character
is typed. This allows the user to backspace over mistakes and
correct them. Java does not allow you to put the console into
"raw" mode. */
import java.io.*;
public class Echo {
public static void main(String[] args) {
try {
echo(System.in);
}
catch (IOException ex) {
System.err.println(ex);
}
}
public static void echo(InputStream in) throws IOException {
while (true) {
// Notice that although a byte is read, an int
// with value between 0 and 255 is returned.
// Then this is converted to an ISO Latin-1 char
// in the same range before being printed.
int i = in.read();
// -1 is returned to indicate the end of stream
if (i == -1) break;
// without the cast a numeric string like "65"
// would be printed instead of the character "A"
char c = (char) i;
System.out.print(c);
}
System.out.println();
}
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}