2013-02-18 40 views
1

我正在使用下面的代碼將文件鏈接到資源文件夾並閱讀文件和書寫,然後我通過第三方應用程序打開PDF文件。PDF文件不能使用類加載器打開

這是我的代碼;

public void readFile(){ 
     InputStream fileInputStream= null; 
     String filePath = "PDF/" + name + ".pdf"; 
     ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
     try { 
      fileInputStream = classLoader.getResourceAsStream(filePath); 
      int size = fileInputStream.available(); 
      byte[] buffer = new byte[size]; 
      fileInputStream.read(buffer); 
      fileInputStream.close(); 

      writeFile(buffer, name); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public void writeFile(byte[] buffer, String fileName){ 
     try { 
      File root = Environment.getExternalStorageDirectory(); 
      FileOutputStream fileOutputStream = null; 

      if (root.canWrite()){ 
       File pdffile = new File("/sdcard/aaa/bbb"); 
       pdffile.mkdirs(); 
       System.out.println(" pdf path "+pdffile.toString()); 
       File outputFile = new File(pdffile.toString()); 
       fileOutputStream = new FileOutputStream(
         outputFile+"/" + fileName + ".pdf"); 
       BufferedOutputStream bos = new BufferedOutputStream(
         fileOutputStream); 
       bos.write(buffer); 
       bos.flush(); 
       bos.close(); 

       } 
      } catch (IOException e) { 
      Log.e("Rrror", "Could not write file " + e.getMessage()); 
     } 

    } 

File f = new File("/sdcard/aaa/bbb/"+name+".pdf"); 
Uri path = Uri.fromFile(f); 
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(path, "application/pdf"); 

現在一些文件中,閱讀開放正常,但一些文件它不是打開它說ķ

"This Document cannot be opened".

但是,如果使用入資產管理打開的文件它完美的罰款。

這裏有什麼問題,

+1

您是否檢查位於「/ sdcard/AAA/BBB /「?還是隻在資源?如果您檢查並比較它們,並且它們有所不同,這可能是由於您假定InputStream.available()返回了正確的底層資源大小:它只包含*可以讀取的字節數的估計值(或跳過),而不會被下一次調用該輸入流的方法所阻塞。*(根據JDK JavaDocs) – mkl 2013-02-18 10:59:25

+0

@mkl thnaks,yes您的答案是正確的,文件大小不同,該怎麼辦? – Goofy 2013-02-18 11:08:44

回答

3

資源和提取副本的大小「/ SD卡/ AAA/BBB」不同。這是由於InputStream.available()返回底層資源的正確大小的錯誤假設:它僅包含對可從此輸入流讀取(或跳過)的字節數的估計,而不會因下一次調用方法而被阻塞對於此輸入流(根據JDK JavaDocs)。

因此,您必須更改將輸入流複製到字節數組的代碼。這個主題已經在StackOverflow上討論過了,例如,比照Convert InputStream to byte[] in Java(只考慮忽略這個問題是指圖像文件的問題,例如@RichSeller使用Apache commons-io的問題,或者不引入新的依賴關係,@ Adamamski使用ByteArrayOutputStreambyte[]緩衝區, (is.read(...) != -1),也可能有更復雜的nio解決方案,但是什麼......;)

+0

可以請你幫我在我的情況下添加哪一個?我很困惑? – Goofy 2013-02-18 11:39:54

+1

如果你的項目已經依賴Apache commons-io,試試@ RichSeller的'IOUtils.toByteArray(is)';否則使用@ Adamski的'ByteArrayOutputStream buffer = ...; while(...){...} ... buffer.toByteArray();' – mkl 2013-02-18 11:44:23

+0

好的,我正在嘗試@Adamski的靈魂,請稍候,但是這個數字是什麼16384 – Goofy 2013-02-18 11:47:35