jub*_*lop 4 java bytearray inputstream intellij-idea
我正在修复我的应用程序中的一些潜在错误。我正在使用声纳来评估我的代码。我的问题是这样的:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是否意味着字节数组为空?为什么会被忽略?我从来没有使用过字节,所以我想知道这个问题究竟意味着什么以及我如何解决它。感谢您的帮助!
这是否意味着字节数组为空?
否 - 这不是错误
从定义中查看read(byte[])方法:
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 {
....
}
}
Run Code Online (Sandbox Code Playgroud)
那么IDE指示什么?是您省略了 read 方法的结果- 如果已到达流的末尾,则是实际读取的字节数或 -1。
怎么修?
如果您关心读取到字节缓冲区的字节数:
// define variable to hold count of read bytes returned by method
int no_bytes_read = re.read(encodedKey);
Run Code Online (Sandbox Code Playgroud)
你为什么要关心???
例如:
// 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 ?
Run Code Online (Sandbox Code Playgroud)
我鼓励你阅读更多关于io和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/
| 归档时间: |
|
| 查看次数: |
6435 次 |
| 最近记录: |