簡體   English   中英

IntelliJ“ inputstream.read的結果被忽略”-如何解決?

[英]IntelliJ “result of inputstream.read is ignored” - how to fix?

我正在修復應用程序中的一些潛在錯誤。 我正在使用Sonar評估我的代碼。 我的問題是這樣的:

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;
}

這是否意味着字節數組為空? 為什么它被忽略? 我從未使用過字節,因此我想知道這個問題的確切含義以及如何解決。 感謝您的協助!

這是否意味着字節數組為空?

否-這不是錯誤

從以下定義看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 {

       ....
    }

}

那么IDE指示什么呢? 您省略了read方法的結果 -這是實際讀取的字節數,如果已到達流的末尾,則為-1。

怎么修?

如果您關心將多少字節讀取到字節緩沖區:

  // define variable to hold count of read bytes returned by method 
  int no_bytes_read = re.read(encodedKey);

為什么你應該關心???

  1. 因為當您從流中讀取數據時,通常是作為緩沖區傳遞參數,特別是當您不知道流所承載的數據大小或要按部分讀取數據時(在這種情況下,您傳遞的是byteed數組decryptedBuferSize size-> new byte [decryptBuferSize] )。
  2. 在開始時,字節緩沖區(字節數組)為空(用零填充)
  3. 方法read()/ read(byte [])從流中讀取一個或多個字節
  4. 要知道“映射/從流到緩沖區讀取/讀取了多少個字節”,您必須獲取read(byte [])方法的結果,這很有用,因為您無需檢查緩沖區的內容。
  5. 仍然需要從緩沖區中獲取數據/然后您需要知道緩沖區中數據的開始和結束偏移量

例如:

 // 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 ? 

我鼓勵您閱讀有關ionio 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM