How to Read a Byte Array of Size 1024 in Java

The contracts of the read methods for InputStream and Reader classes and their subclasses are complicated with regard to filling byte or character arrays. According to the Coffee API [API 2014] for the class InputStream, the read(byte[] b) method and theread(byte[] b, int off, int len) method provide the following beliefs:

The number of bytes actually read is returned as an integer. This method blocks until input information is bachelor, cease of file is detected, or an exception is thrown.

According to the Java API for theread(byte[] b, int off, int len) method:

An attempt is fabricated to read every bit many as len  bytes, only a smaller number may be read, possibly zero.

Bothread methods render as soon as they find bachelor input data. As a consequence, these methods can stop reading information before the assortment is filled considering the available data may be insufficient to fill the array.

The documentation for the analogousread methods inReader return the number of characters read, which implies that they also need not fill up thechar array provided as an statement.

Ignoring the effect returned by the read() methods is a violation of EXP00-J. Do non ignore values returned by methods. Security issues can ascend even when return values are considered because the default beliefs of the read() methods lacks whatever guarantee that the entire buffer array is filled. Consequently, when using read() to fill an array, the program must bank check the return value of read() and must handle the case where the array is only partially filled. In such cases, the programme may try to fill up the remainder of the array, or work only with the subset of the array that was filled, or throw an exception.

This rule applies only to read() methods that take an array argument. To read a single byte, use the InputStream.read() method that takes no arguments and returns an int. To read a unmarried grapheme, use a Reader.read() method that takes no arguments and returns the character read as an int.

Noncompliant Code Example (i-argumentread())

This noncompliant code example attempts to read 1024 bytes encoded in UTF-eight from an InputStream and return them as a Cord. It explicitly specifies the graphic symbol encoding used to build the cord, in compliance with STR04-J. Utilise compatible character encodings when communicating string data between JVMs.

public static String readBytes(InputStream in) throws IOException {   byte[] information = new byte[1024];   if (in.read(information) == -one) {     throw new EOFException();   }   render new String(data, "UTF-8"); }          

The programmer'southward misunderstanding of the general contract of the read() method tin can event in failure to read the intended data in total. It is possible that less than 1024 bytes exist in the stream, mayhap considering the stream originates from a file with less than 1024 bytes. It is also possible that the stream contains 1024 bytes but less than 1024 bytes are immediately bachelor, perhaps considering the stream originates from a TCP socket that sent more than bytes in a subsequent package that has non arrived notwithstanding. In either case,read() volition return less than 1024 bytes. It indicates this through its render value, only the plan ignores the render value and uses the entire array to construct a string, even though any unread bytes will fill the cord with null characters.

Noncompliant Code Case (three-argumentread())

This noncompliant code example uses the iii-statement version of read() to read 1024 bytes encoded in UTF-8 from anInputStream and return them as aString.

public static String readBytes(InputStream in) throws IOException {   byte[] data = new byte[1024];   int starting time = 0;   if (in.read(data, offset, information.length - offset)) != -1) {     throw new EOFException();   }   return new String(data, "UTF-eight"); }          

Even so, this code suffers from the same flaws as the previous noncompliant code instance. Again, theread() method can return less than 1024 bytes, either because 1024 bytes are simply not bachelor, or the latter bytes take non arrived in the stream nevertheless.  In either example,read() returns less than 1024 bytes, the remaining bytes in the array remain with zero values, yet the entire array is used to construct the string.

Compliant Solution (Multiple Calls to read())

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 beyond buffers by deferring construction of the upshot string until the information has been fully read. (see IDS10-J. Practice not assume every character in a string is the aforementioned size for more than information).

public static String readBytes(InputStream in) throws IOException {   int first = 0;   int bytesRead = 0;   byte[] information = new byte[1024];   while ((bytesRead = in.read(information, offset, data.length - beginning))     != -i) {     first += bytesRead;     if (offset >= data.length) {       intermission;     }   }   String str = new Cord(information, 0, offset, "UTF-8");   return str; }          

Compliant Solution (readFully())

The no-argument and 1-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 cease of input before the required number of bytes have been read; they throw IOException if another I/O error occurs.

public static String readBytes(FileInputStream fis)                                throws IOException {   byte[] data = new byte[1024];   DataInputStream dis = new DataInputStream(fis);   dis.readFully(data);   String str = new Cord(information, "UTF-8");   render str; }          

Risk Assessment

Incorrect use of the read() method can result in the wrong number of bytes being read or character sequences being interpreted incorrectly.

Dominion

Severity

Likelihood

Remediation Price

Priority

Level

FIO10-J

Low

Unlikely

Medium

P2

L3

Automated Detection

Bibliography


cunninghamfacen1987.blogspot.com

Source: https://wiki.sei.cmu.edu/confluence/display/java/FIO10-J.+Ensure+the+array+is+filled+when+using+read%28%29+to+fill+an+array

0 Response to "How to Read a Byte Array of Size 1024 in Java"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel