繁体   English   中英

扫描仪无法从 zipinputstream 读取数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM