2016-06-27 53 views
1

我正在修復我的應用程序中的一些潛在錯誤。我使用Sonar來評估我的代碼。我的問題是這樣的:IntelliJ「inputstream.read的結果被忽略」 - 如何解決?

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

這是否意味着字節數組是空的?爲什麼會被忽略? 我從來沒有使用字節,所以我想知道這個問題究竟意味着什麼,以及我如何解決它。感謝您的協助!

回答

2

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

NO - 這是no't錯誤

看看讀(字節[])從定義方法:

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什麼?您省略了讀取方法的結果 - 這是實際讀取的字節數,如果已到達流尾,則爲-1。

如何解決?

如果u關心了多少字節讀取字節的緩衝區

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

爲什麼要照顧???

  1. 因爲當你從流中讀出要傳遞作爲參數通常是一個緩衝器特別是當不知道由流正在進行數據的大小或要通過的部分來讀取(在這種情況下,你傳遞字節decryptedBuferSize大小數組 - >新字節[decryptBuferSize])。
  2. 開頭字節緩衝器(字節陣列)是空的(用零填充)
  3. 方法讀()/讀(字節[])中讀取來自流的一個或多個字節
  4. 要知道多少字節被「映射/從流讀取到緩衝區」,您必須得到讀取(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/