0

I need to use uri to load file. Uri cannot be converted to absolute path (external volume).

I found example:

private String readTextFromUri(Uri uri) throws IOException {
    InputStream inputStream = getContentResolver().openInputStream(uri);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
    }
    fileInputStream.close();
    parcelFileDescriptor.close();
    return stringBuilder.toString();
}

But I can't understand how to modify it to read in bytes.

Daimonium
  • 29
  • 8
  • You mean read the file and hook it into a byte array right? –  Jan 23 '17 at 08:07
  • Simple Google search: http://stackoverflow.com/questions/35939527/android-how-read-file-to-byte-array. I'm already using FileInputStream for absolute paths, but now I need to make it working with uri. – Daimonium Jan 23 '17 at 08:10
  • `"to read in bytes"`? what do you mean? you have: `InputStream inputStream = getContentResolver().openInputStream(uri);` so use that `InputStream` for reading – pskink Jan 23 '17 at 08:16
  • @pskink, I see... But how exactly I should use it? – Daimonium Jan 23 '17 at 08:20
  • how to use `InputStream`? it has `int read (byte[] b)` method for example – pskink Jan 23 '17 at 08:21

2 Answers2

1

As pskink said, your main problem is that you are wrapping your InputStream in a Reader. A Reader is meant to decode bytes into characters, which is, by defintion, what you want to avoid. You need to allocate a buffer and use the InputStream's read method to fill it.

Keep in mind that you have to know the amount of incoming bytes or read multiple times while processing the already received data.

Alternatively, you could use the read method to get an int, check whether the stream has ended, then cast that int to a byte and process one by one. But usually, you want to use a buffer, since that's faster.

Silverclaw
  • 1,316
  • 2
  • 15
  • 28
  • Something like this? `InputStream inputstream = context.getContentResolver().openInputStream(uri); data = new byte[4*1024]; int bytesRead = inputstream.read(data); while(bytesRead != -1) { bytesRead = inputstream.read(data); } inputstream.close();` – Daimonium Jan 23 '17 at 10:16
  • It's hard to read in a comment, but it looks like a good start. ;) – Silverclaw Jan 23 '17 at 10:18
-1
URL url = new URL("http://www.craftychild.com/image-files/kids-paint-center.jpg");
BufferedImage image = ImageIO.read(url);
File file = new File("D:\\picture\demo.jpg");
ImageIO.write(image, "jpg",file);