嗨,大家好,我試圖將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;
}
davidxxx想對您的答案,但我需要的是使用資源文件夾中的文件位置,我不應該使用像「c://java//files//test.pdf」這樣的路徑我正是這樣使用它來比較結果 –
你的歡迎:)我的回答應該回答這個問題:「你可以在類路徑中移動文件(如果有意義的話),」 – davidxxx