简体   繁体   English

扫描仪无法从 zipinputstream 读取数据

[英]scanner can't read data from zipinputstream

I have a piece of code for reading CSV file from a zipInputStream.我有一段用于从 zipInputStream 读取 CSV 文件的代码。 I am trying to read all entries of this zipInputStream, so if there is txt, pdf.我正在尝试读取此 zipInputStream 的所有条目,因此如果有 txt、pdf。 I don't need any of them, the zip file supposed to be impressed by one and only one CSV file, if not, throw an error.我不需要它们中的任何一个,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")
}

however I have tested this with a zip file impressed by a pdf and a CSV, CSV is not empty.但是我已经用 pdf 和 CSV 留下深刻印象的 zip 文件对此进行了测试,CSV 不是空的。 it should print out a new line but it gives me "there is no newline".它应该打印出一个新行,但它给了我“没有换行符”。 is there any logic issue I didn't see?有什么我没看到的逻辑问题吗?

Try this code.试试这个代码。 It accepts the path to your zip file and returns a byte array with the CSV file content inside it.它接受 zip 文件的路径并返回一个字节数组,其中包含 CSV 文件内容。 If there are more files inside the ZIP or the CSV file is not found, then exceptions are thrown.如果 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