2011-11-24 20 views

回答

3

使用IOUtils.toByteArray從Apache公地IO庫。這是我知道的最簡單和最安全的方式。 commons-io庫本身很小。

事情是這樣的:

FileInputStream fileStream = null; 
try { 
    fileStream = new FileInputStream("/sdcard/tets.png"); 
    final byte[] data = IOUtils.toByteArray(fileStream); 
    // Do something useful to the data 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    IOUtils.closeQuietly(fileStream); 
} 
0

試試這個代碼,

public static byte[] getBytesFromFile(File file) throws IOException { 
     InputStream is = new FileInputStream(file); 
     long length = file.length(); 

     if (length > Integer.MAX_VALUE) { 
      // File is too large 
     } 

     byte[] bytes = new byte[(int)length]; 

     int offset = 0; 
     int numRead = 0; 
     while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { 

      offset += numRead; 
     } 

     if (offset < bytes.length) { 
      throw new IOException("Could not completely read file "+file.getName()); 
     } 

     is.close(); 
     return bytes; 
    } 
+0

此功能泄露的InputStream如果is.read(..)拋出IOException的is.close()語句沒有按」在這種情況下得到執行。 –

相關問題