Skip to content

Instantly share code, notes, and snippets.

@dmitriy-chernysh
Last active December 19, 2017 16:20
Show Gist options
  • Save dmitriy-chernysh/7fa86aa44969bb8d09d9fb821c2d7d38 to your computer and use it in GitHub Desktop.
Save dmitriy-chernysh/7fa86aa44969bb8d09d9fb821c2d7d38 to your computer and use it in GitHub Desktop.
Java. readBytes from File
private static byte[] readBytes(@NonNull File file) throws IOException {
byte[] byteArray = null;
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = new FileInputStream(file);
outputStream = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 4];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
outputStream.write(b, 0, bytesRead);
}
byteArray = outputStream.toByteArray();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}catch (IOException e) {
//log eroro here
}
}
return byteArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment