-1
如何獲得來自例如存儲在EG的本地文件系統中的圖像一個byte []:/sdcard/tets.png
如何從本地文件中獲取字節[],例如/sdcard/tets.png?
如何獲得來自例如存儲在EG的本地文件系統中的圖像一個byte []:/sdcard/tets.png
如何從本地文件中獲取字節[],例如/sdcard/tets.png?
使用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);
}
試試這個代碼,
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;
}
此功能泄露的InputStream如果is.read(..)拋出IOException的is.close()語句沒有按」在這種情況下得到執行。 –