I'm working on fixing some potential bugs in my application. I'm using Sonar to evaluate my code. My issue is this:
private Cipher readKey(InputStream re) throws Exception {
byte[] encodedKey = new byte[decryptBuferSize];
re.read(encodedKey); //Check the return value of the "read" call to see how many bytes were read. (the issue I get from Sonar)
byte[] key = keyDcipher.doFinal(encodedKey);
Cipher dcipher = ConverterUtils.getAesCipher();
dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
return dcipher;
}
Does this mean that the byte array was empty? Why is it being ignored? I've never worked with bytes so I was wondering what exactly this issue means and how I can address it. I appreciate your assistance!
Does this mean that the byte array was empty?
NO - this is no't an error
look at read(byte[]) method from definition of:
public abstract class InputStream extends Object implements Closeable {
/**
* Reads up to {@code byteCount} bytes from this stream and stores them in
* the byte array {@code buffer} starting at {@code byteOffset}.
* Returns the number of bytes actually read or -1 if the end of the stream
* has been reached.
*
* @throws IndexOutOfBoundsException
* if {@code byteOffset < 0 || byteCount < 0 || byteOffset + byteCount > buffer.length}.
* @throws IOException
* if the stream is closed or another IOException occurs.
*/
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
....
}
}
so what the IDE indicating? is that you omitting the result of read method - which is the number of bytes actually read or -1 if the end of the stream has been reached.
How to fix?
if u care how many bytes were read to byte buffer:
// define variable to hold count of read bytes returned by method
int no_bytes_read = re.read(encodedKey);
why you should care ???
for example:
// on left define byte array = // on right reserve new byte array of size 10 bytes
byte[] buffer = new byte[10];
// [00 00 00 00 00 00 00 00 00 00] <- array in memory
int we_have_read = read(buffer); // assume we have read 3 bytes
// [22 ff a2 00 00 00 00 00 00 00] <- array after read
have we reached the end of steram or not ? do we need still to read ?
we_have_read ? what is the value of this variable ? 3 or -1 ?
if 3 ? do we need still read ?
or -1 ? what to do ?
i encourage you to read more about io and nio api
http://tutorials.jenkov.com/java-nio/nio-vs-io.html
https://blogs.oracle.com/slc/entry/javanio_vs_javaio
http://www.skill-guru.com/blog/2010/11/14/java-nio-vs-java-io-which-one-to-use/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.