从流创建PDF的问题

时间:2016-03-08 12:57:33

标签: android pdf

我正在从服务器接收流。该流代表PDF,我知道它是一个pdf文件。我收到了,并以这种方式存储在手机中:

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();
}
}

这样,文件就被创建了,但是我使用文件浏览器尝试打开pdf,然后打开,但它是空白的。

对我做错了什么的想法?

谢谢。

1 个答案:

答案 0 :(得分:0)

假设您将文档(pdf)作为byteArray(documentBytes) 我会:

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) {
            }
        }
    }

然后,您可以使用createUri()

收到的uri显示该文档