Reputation: 93
I am trying to make user pick an image from gallery, display it in imageView, and at the same time, create a byte array of the same file.
After debugging:
'new File(filepath)' executed no problem, with a valid filesystem path.
but it always skips 'ByteArrayOutputStream baos = new ByteArrayOutputStream();' to the IOException with a java.ioFileNotFoundException
any idea what im doing wrong?
or is there a more efficient way i can just convert a byte of a file to a HEX character, and send each HEX char until the last byte of the file?
try {
File myFile = new File(imageUri.getPath());
String filepath = myFile.getAbsolutePath();
Log.d("onActivityResult", "filepath: " + filepath);
FileOutputStream fos = new FileOutputStream ( new File(filepath) );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
Toast.makeText(this, "Byte buffer error.", Toast.LENGTH_LONG).show();
}
Upvotes: 0
Views: 542
Reputation: 1006514
any idea what im doing wrong?
You think that a Uri
always points to a file.
If the scheme of the Uri
is file
, then getPath()
will be a filesystem path. Depending on how you got the Uri
, that filesystem path may be usable.
Most of the time, the Uri
will have a different scheme, typically content
. For such a Uri
, getPath()
is meaningless, just as getPath()
is meaningless for a Uri
like https://stackoverflow.com/questions/46457384/error-when-converting-file-to-byte-array-java-iofilenotfoundexception
.
For a Uri
with a scheme of content
(or file
, or android.resource
), use a ContentResolver
and openInputStream()
to get an InputStream
on the content identified by the Uri
.
Even if you fix that, you will crash most of the time with an OutOfMemoryError
, as you will not have a single contiguous block of free heap space to load the entire content that the user chose.
Upvotes: 2