当我尝试使用" read"将普通PDF文件中的字节读取到字节数组中时在Java中,函数正确加载,其大小与原始PDF文件的大小相同。
Path file_path = Paths.get("D:\\Zip Test Client", "vadClient1.pdf");
byte[] ByteArray= Files.readAllBytes(file_path);
FileOutputStream fos = new FileOutputStream(new File("E:\\newFinalPDF.pdf"));
但是当我从位于压缩文件夹内的同一PDF文件中读取字节时,read函数只读取8843个字节(原始大小为194471),其余全部为0。
zipFile = new ZipFile(new File("D:\\Zip test Server\\ZipTestFolderOnServer.zip"));
long count = zipFile.size();
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
System.out.println("New File starting");
ZipEntry zipEntry = entries.nextElement();
System.out.println(zipEntry.getName());
InputStream fis = zipFile.getInputStream(zipEntry);
byte[] fileToBytes = new byte[(int)zipEntry.getSize()];
FileOutputStream fos = new FileOutputStream(new File("E:\\ContentZipped_" + zipEntry.getName()));
fis.read(fileToBytes);
fos.write(fileToBytes);
fis.close();
Thread.sleep(1000);
--count;
}
这种行为有什么解释?
编辑1: - 我不是在寻找第三方集成,例如Tika或POI。
答案 0 :(得分:2)
通过简化代码,让它减少错误(并减少内存消耗),使用它来复制zip条目的内容:
try (InputStream fis = zipFile.getInputStream(zipEntry)) {
Files.copy(fis, Paths.get("E:\\ContentZipped_" + zipEntry.getName()));
}
答案 1 :(得分:0)
公共类SampleZipExtract {
public static void main(String[] args) {
List<String> tempString = new ArrayList<String>();
StringBuffer sbf = new StringBuffer();
File file = new File("C:\\Users\\xxx\\Desktop\\abc.zip");
InputStream input;
try {
input = new FileInputStream(file);
ZipInputStream zip = new ZipInputStream(input);
ZipEntry entry = zip.getNextEntry();
BodyContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
while (entry!= null){
if(entry.getName().endsWith(".txt") ||
entry.getName().endsWith(".pdf")||
entry.getName().endsWith(".docx")){
System.out.println("entry=" + entry.getName() + " " + entry.getSize());
parser.parse(input, textHandler, metadata, new ParseContext());
tempString.add(textHandler.toString());
}
}
zip.close();
input.close();
for (String text : tempString) {
System.out.println("Apache Tika - Converted input string : " + text);
sbf.append(text);
System.out.println("Final text from all the three files " + sbf.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}