Search code examples
javaandroidodata4j

Handling a large-ish binary file, streaming to storage


I am using Odata4j and my entity has one Data field which is a binary file. When viewing through a browser it shows as a Base64 string.

How can I get this file onto my Android device?

I have tried the following to get a byte[]...

String stringData = entity.getProperty("Data").getValue().toString();
byte[] data = Base64.decodeBase64(stringData);

But this is just giving me a small array of about 7 bytes. However, when I debug I can see the entity data has a large binary value.

I also have an issue with a second file which is producing an "out of memory" exception, ideally I would like to be able to download this file straight to the device's storage as a stream/buffer, is this possible?

To be clear, the question is: How to stream this data straight onto the device's storage?


Solution

  • I solved this problem without using OData. There is a URL available that will return just the binary data. So with this URL I can use other Java classes to stream the data directly to disk.

    So with this URL:

    www.example.com/OData.svc/File/Data/$value

    (which returns just the binary data)

    We can create a URL connection and download it:

    URL url = new URL(webPage);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
    File file = new File(dir, fileName);//need to create a file based on your storage paths
    
    FileOutputStream out = new FileOutputStream(file);
    InputStream in = urlConnection.getInputStream();
    
    byte[] buffer = new byte[1024];
    int i = 0;
    while ((i = in.read(buffer)) > 0) {
        out.write(buffer, 0, i);
    }
    
    out.flush();
    out.close();
    in.close();