...
The default implementation of this method blocks until the requested amount of input data
lenhas been read, end of file is detected, or an exception is thrown. Subclasses are encouraged to provide a more efficient implementation of this method.
However, the read(byte[] b) method:
reads some number of bytes from the input stream and stores them into the buffer array
b. The number of bytes actually read is returned as an integer. The number of bytes read is, at most, equal to the length ofb.
...
This noncompliant code example attempts to read 1024 bytes encoded in UTF-8 from an InputStream and return them as a String. It explicitly specifies the character encoding used to build the string, in compliance with rule IDS13-J. Use compatible encodings on both sides of file or network IO.
| Code Block | ||
|---|---|---|
| ||
public static String readBytes(InputStream in) throws IOException {
byte[] data = new byte[1024];
if (in.read(data) == -1) {
throw new EOFException();
}
return new String(data, "UTF-8");
}
|
...
This compliant solution reads all the desired bytes into its buffer, accounting for the total number of bytes read and adjusting the remaining bytes' offset, consequently ensuring that the required data is read in full. It also avoids splitting multibyte encoded characters across buffers by deferring construction of the result string until the data has been fully read. (See rule IDS10-J. Do not assume every character in a string is the same size for more information.)
| Code Block | ||
|---|---|---|
| ||
public static String readBytes(InputStream in) throws IOException {
int offset = 0;
int bytesRead = 0;
byte[] data = new byte[1024];
while ((bytesRead = in.read(data, offset, data.length - offset))
!= -1) {
offset += bytesRead;
if (offset >= data.length) {
break;
}
}
String str = new String(data, "UTF-8");
return str;
}
|
...
The no-argument and one-argument readFully() methods of the DataInputStream class guarantee that either all of the requested data is read or an exception is thrown. These methods throw EOFException if they detect the end of input before the required number of bytes have been read; they throw IOException if some other I/O error occurs.
| Code Block | ||
|---|---|---|
| ||
public static String readBytes(FileInputStream fis)
throws IOException {
byte[] data = new byte[1024];
DataInputStream dis = new DataInputStream(fis);
dis.readFully(data);
String str = new String(data, "UTF-8");
return str;
}
|
...
[API 2006] | Class |
8.1, Handling Errors with Return Codes | |
Chapter 7, Data Streams, Reading Byte Arrays | |
|