Skip to content

Instantly share code, notes, and snippets.

@nerdstrom
Created January 10, 2019 19:18
Show Gist options
  • Save nerdstrom/41a79d1812d835639f5223d110ac1eaf to your computer and use it in GitHub Desktop.
Save nerdstrom/41a79d1812d835639f5223d110ac1eaf to your computer and use it in GitHub Desktop.
read file (from downloads directory, or resources) as byte array on android
// reads a files content by a given filename and returns it as a byte[]
// returns null if there are problems reading the file
public byte[] readBytesFromFileInDownloadsDir(String filename) {
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// we look for the filename in the "Downloads" directory on the sdcard
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename);
try {
return readBytesFromInputStream(new FileInputStream(file), file.length());
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found " + e.getMessage());
return null;
}
}
else {
Log.e(TAG, "Can't read file. External Storage isn't mounted?");
return null;
}
}
// reads a raw resource by a given id and returns it as a byte[]
// returns null if there are problems reading the resource
public byte[] readBytesFromRawResource(int resourceId) {
// get an AssetFileDescriptor to get an inputstream and the length of the file
AssetFileDescriptor fileDescriptor = getResources().openRawResourceFd(resourceId);
try {
return readBytesFromInputStream(fileDescriptor.createInputStream(), fileDescriptor.getLength());
} catch (IOException e) {
Log.e(TAG, "Error creating inputstream. " + e.getMessage());
return null;
}
}
// reads an inputStream and returns it as a byte[]
// returns null if there are problems reading the inputStream
public byte[] readBytesFromInputStream(InputStream inputStream, long bytesToRead) {
if(bytesToRead > Integer.MAX_VALUE) {
Log.e(TAG, "file is too large to read into byte array");
return null;
}
byte buffer[] = new byte[(int)bytesToRead];
try {
if ( inputStream.read(buffer) == -1 ) {
throw new IOException("EOF reached while reading buffer (bytesToRead: " + bytesToRead);
}
} catch (IOException e) {
Log.e(TAG, "Error reading bytes from inputstream. " + e.getMessage());
buffer = null;
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
Log.e(TAG, "Error closing inputstream" + e.getMessage());
}
}
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment