2015-03-13 343 views
0

語境使用ByteArrayInputStream進行的FileInputStream的

我適配現有項目的部分到GAE項目。原來的項目使用FileInputStreamFileOutputStream但由於GAE不接受FileOutputStream我與ByteArrayInputStreamByteArrayOutputStream替換它們。原始代碼加載了一些本地文件,我用Datastore Entities替換了那些將這些文件的內容保存在其某個屬性中的文件。

問題

它主要似乎工作,但我得到一個ArrayIndexOutOfBoundsException在這段代碼:

private byte[] loadKey(Entity file) { 
     byte[] b64encodedKey = null; 
     ByteArrayInputStream fis = null; 
     try { 
      fis = fileToStreamAdapter.objectToInputStreamConverter(file); 
      b64encodedKey = new byte[(int) fis.available()]; 
      fis.read(b64encodedKey); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fis != null) 
        fis.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return b64encodedKey; 
    } 

fileToStreamAdapter.objectToInputStreamConverter(file)需要Datastore Entity並打開其屬性之一的內容爲ByteArrayInputStream

原始代碼:

private byte[] loadKey(String path) { 
     byte[] b64encodedKey = null; 
     File fileKey = new File(path); 
     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(fileKey); 
      b64encodedKey = new byte[(int) fileKey.length()]; 
      fis.read(b64encodedKey); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fis != null) 
        fis.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     return b64encodedKey; 
    } 

有我丟失的東西在FileInputStreamByteArrayInputStream之間的差異可能導致這個錯誤?

+0

什麼是異常堆棧? – 2015-03-13 13:44:07

回答

0

在我看來,如果objectToInputStreamConverter創建ByteArrayInputStream使用ByteArrayInputStream(byte[] buf)那麼它可以只返回byte []參數,並且不需要再讀取任何東西,更不用說所有的錯誤處理了。

+0

你說得對,由於想堅持原來的代碼,我做了一些不必要的步驟。最後,我只需要從實體中獲取內容並將其轉換爲字節[]。 – LisaMM 2015-03-13 14:04:27

0

fis.available()不是輸入流的大小,到底有多少數據,此時緩衝區可用。

如果你需要使用像這樣返回從輸入流中,你必須將它複製字節:

ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 

int l; 
byte[] data = new byte[16384]; 
while ((l = fis.read(data, 0, data.length)) != -1) { 
    buffer.write(data, 0, l); 
} 
buffer.flush(); 
return buffer.toByteArray(); 

或更好,我們IOUtilscommons-io

相關問題