I have a piece of code for reading CSV file from a zipInputStream. I am trying to read all entries of this zipInputStream, so if there is 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.
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. 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. If there are more files inside the ZIP or the CSV file is not found, then exceptions are thrown.
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);
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.