![](/img/trans.png)
[英]Why ZipInputStream can't read the output of ZipOutputStream?
[英]scanner can't read data from zipinputstream
我有一段用於從 zipInputStream 讀取 CSV 文件的代碼。 我正在嘗試讀取此 zipInputStream 的所有條目,因此如果有 txt、pdf。 我不需要它們中的任何一個,zip 文件應該被一個且只有一個 CSV 文件留下深刻印象,如果沒有,則拋出錯誤。
int CSVFile = 0;
Scanner scanner = null;
String line = "";
while((entry = zipinputstream.getNextEntry())!=null){
if(entry.getName.endsWith(".csv")){
CSVFile += 1;
scanner = new Scanner(zipinputstream);
}
}
if(CSVFile > 1 || CSVFile == 0){
throw new Exception("error");
}
if(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
} else {
throw new Exception("there is no newline")
}
但是我已經用 pdf 和 CSV 留下深刻印象的 zip 文件對此進行了測試,CSV 不是空的。 它應該打印出一個新行,但它給了我“沒有換行符”。 有什么我沒看到的邏輯問題嗎?
試試這個代碼。 它接受 zip 文件的路徑並返回一個字節數組,其中包含 CSV 文件內容。 如果 ZIP 中有更多文件或未找到 CSV 文件,則會引發異常。
public byte[] readCSVFileAsInputStream(String filePath) {
File file = new File(filePath);
try (ZipFile zipFile = new ZipFile(file))
{
Enumeration<? extends ZipEntry> entries = zipFile.entries();
ZipEntry entry = entries.nextElement();
if(entry == null){
throw new IllegalArgumentException("no files found inside: " + filePath);
}
if (entries.hasMoreElements())
{
throw new IllegalArgumentException("only one CSV file is accepted inside: " + filePath);
}
if (!FilenameUtils.getExtension(entry.getName()).equalsIgnoreCase("csv"))
{
throw new IllegalArgumentException("only one CSV file is accepted inside: " + filePath);
}
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream())
{
IOUtils.copy(zipFile.getInputStream(entry), byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
catch (IOException exception)
{
throw new UncheckedIOException(MessageFormat.format("error while reading {0}", filePath), exception);
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.