2017-01-22 32 views
0

嗨,大家好,我試圖將PDF文件轉換爲字節數組,但它無法爲我工作,當我試圖從classLoader使用classLoader獲取文件,它到字節數組它不起作用我沒有一個空數組,但獲取數組的長度不正確,當我寫這個字節數組作爲一個文件我有一個損壞的文件,我不能打開它。資源classPath文件轉換爲字節數組不工作

當我試圖使用類似於(c://java//files//test.pdf)這樣的路徑獲取文件時,最後一件事情是工作並且字節數組長度沒問題,並且當我將數組寫入文件時我有一些輸入文件。使用的類加載器,並使用路徑獲取文件長度的另一件事是完全一些 我的代碼是:

public static void main(String[] args) { 

     try { 

      // convert file to byte[] 
      byte[] bFile = readBytesFromFile("C:\\TEMP\\test.pdf"); 
      byte[] bytes = readBytesFromFileResources(); 

      System.out.println(bFile.length);//60255 
      System.out.println(bytes.length);//14463 
} 
private static byte[] readBytesFromFile(String filePath) { 

     FileInputStream fileInputStream = null; 
     byte[] bytesArray = null; 

     try { 

      File file = new File(filePath); 
      bytesArray = new byte[(int) file.length()]; 

      //read file into bytes[] 
      fileInputStream = new FileInputStream(file); 
      fileInputStream.read(bytesArray); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (fileInputStream != null) { 
       try { 
        fileInputStream.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

     } 

     return bytesArray; 

    } 

    private static byte[] readBytesFromFileResources() { 


     ClassLoader classLoader = ReadFile.class.getClassLoader(); 
     File file = new File(classLoader.getResource("test.pdf").getFile()); 
     FileInputStream fileInputStream = null; 
     byte[] bytesArray = null; 

     try { 
      bytesArray = new byte[(int) file.length()]; 

      //read file into bytes[] 
      fileInputStream = new FileInputStream(file); 
      fileInputStream.read(bytesArray); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (fileInputStream != null) { 
       try { 
        fileInputStream.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

     } 

     return bytesArray; 

    } 

回答

0

當我試圖使用像 的路徑來獲取文件中的最後一件事(C://的java //files//test.pdf)它的工作和字節數組長度沒問題 當我將數組寫入文件時,我確切地輸入了 中的某個文件。

c://java//files//test.pdf可能不在類路徑中。
所以,你不能使用類加載器加載文件,因爲類加載器將無法找到它。

要麼你移動文件在類路徑中(如果這是有道理的),不管是你在你的問題寫您加載與文件系統相關的方式文件:

File file = new file("c://java//files//test.pdf)"; 
+0

davidxxx想對您的答案,但我需要的是使用資源文件夾中的文件位置,我不應該使用像「c://java//files//test.pdf」這樣的路徑我正是這樣使用它來比較結果 –

+0

你的歡迎:)我的回答應該回答這個問題:「你可以在類路徑中移動文件(如果有意義的話),」 – davidxxx

相關問題