-1

I am receiving a stream from the server. That stream represents a PDF, and I KNOW it is a pdf file. I am receiving it, and storing in the phone this way:

ResponseBody body=response.body();
File dir = new File(Environment.getExternalStorageDirectory() + “/myApp/“+variable+"/“+anotherVariable);
    if (!dir.exists()) { 
        dir.mkdirs();
    }
File file = new File(dir, objetoFichero.get("nombre").getAsString());
try {
    file.createNewFile();
    FileOutputStream fos=new FileOutputStream(file);
    InputStream is = body.byteStream();
    int len = 0;
    byte[] buffer = new byte[1024];
    while((len = is.read(buffer)) != -1) {
    fos.write(buffer,0,len);
}
fos.flush();
fos.close();
is.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

This way, the file is created, but using a file browser I try to open the pdf, and it opens, but it is blank.

Any idea about what I am doing wrong?

Thank you.

Fustigador
  • 6,339
  • 12
  • 59
  • 115
  • I recommend `fos.getFD().sync()` in between `fos.flush()` and `fos.close()`. Beyond that, is the file browser on the device, or are you referring to something on your development machine? Also, if `ResponseBody` is from OkHttp, consider using Okio for streaming the results to the file: http://stackoverflow.com/a/29012988/115145 – CommonsWare Mar 08 '16 at 13:01
  • The file browser is in my device – Fustigador Mar 08 '16 at 13:01

1 Answers1

0

Assuming you have the document (the pdf) as a byteArray (documentBytes) I would:

createUri(this, new File(getCacheDir(), "pdf/whateverNameYouWant.pdf"), documentBytes)

public static Uri createUri(@NonNull final Context context, final File name, @NonNull final byte[] data) throws IOException {
        final File parent = name.getParentFile();
        if (!parent.exists()) {
            FileUtils.mkdirs(parent, null);
        }

        final OutputStream out = new FileOutputStream(name);
        try {
            out.write(data);
        } finally {
            StreamUtils.closeSilently(out);
        }

        return createUri(context, name);
    }

public static void mkdirs(final File dir) {
        if (!dir.mkdirs()) {
            Log.w("File", "Failed to mkdirs: " + dir);
        }
    }

public static void closeSilently(@Nullable final Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (final Throwable ignore) {
            }
        }
    }

You can then show the document with the uri received by createUri()

Greg
  • 689
  • 2
  • 8
  • 23