2016-03-08 69 views
-1

我正在接收來自服務器的流。該流代表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格式,它打開,但它是空的。

有關我在做什麼錯的任何想法?

謝謝。

+0

我建議'文檔fos.getFD()。sync()'在'fos.flush()'和'fos.close()'之間。除此之外,設備上的文件瀏覽器還是您指的是開發計算機上的某些內容?此外,如果'ResponseBody'來自OkHttp,請考慮使用Okio將結果傳輸到文件:http://stackoverflow.com/a/29012988/115145 – CommonsWare

+0

文件瀏覽器位於我的設備中 – Fustigador

回答

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