Problems reading inputStream from Uri and sending via android outputStream

Good afternoon, I'm trying to send a file with an SDCard via an OutputStream . I intend to get the URI from the file name that I have, and then use an InputStream to read the URI and convert to bytes in another for sending. Currently, the code is stuck in get InputStream (as indicated below) and nothing happens.

In addition, I do not know if I am using the URI correctly to get the actual path to the file to send.

Please, any help would be greatly appreciated, because I have been stuck here for a while. Thanks.

My code is:

 public void sendFile() { Log.d(TAG, "sending data"); InputStream inputStream = null; String filePath = Environment.getExternalStorageDirectory() .toString() + "/" + files.get(0); Log.d(TAG, "filepath is" + filePath); Uri uri = Uri.parse(filePath); Log.d(TAG, "obtained input stream here in Activity"); Log.d(TAG, "Uri here is" + uri); // nothing happens after here, Basically stuck!! try { inputStream = getContentResolver().openInputStream(uri); ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); Log.d(TAG, "obtained input stream here in Activity"); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } AppServices.write(byteBuffer.toByteArray()); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } 
+4
source share
2 answers

Using:

 Uri uri = Uri.fromFile(new File(filePath)); 

or just use:

 inputStream = new FileInputStream(filePath); 
+1
source

I tried using InputStream is = ctx.getContentResolver().openInputStream(Uri.parse("file://"+fileUri)); But it doesn’t hurt. It returns the results of an earlier byte. I tried to read this way, but that didn't work either.

 while (is.available() > 0) { outputStream.write(is.read(b)); } 

To do this, I do like this:

The fileUri parameter is a string of the type: "/ mnt / sdcard / DCIM / Camera / 2013-05-07 15.53.47.jpg"

 public static byte[] getImageAsBytes(String fileUri) throws IOException { if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { return null; } //Get file stream FileInputStream is = new FileInputStream(fileUri); //create output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //create buffer byte[] b = new byte[1024]; //Read the input to the bytestream int len = 0; while((len = is.read(b)) != -1){ outputStream.write(b, 0, len); } is.close(); //convert to bytearray final byte[] byteArray = outputStream.toByteArray(); outputStream.close(); return byteArray; } 
0
source

Source: https://habr.com/ru/post/1389519/


All Articles