Error when i am trying to create a zip from 2 files

Yagami Light :

I am trying to combine 2 files in one zip file

myMainMethod

private void downloadFileByTypeInner(StaticDocument file, String productCode, int productVersion) throws IOException, TechnicalException {
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletResponse response = (HttpServletResponse) ec.getResponse();
    String distrib = MultinetFrontHelper.getDefaultDitrib();
    String realPath = findRealPath(ec, file.getPath().replace("{DISTRIB}", distrib));
    String downloadName = file.getDownloadFileName() != null ? file.getDownloadFileName() : file.getPath();

    if (file.getAction() == null || file.getAction().trim().isEmpty() || file.getAction().equals("download")) {
        List<java.io.File> l = new ArrayList<>();
        java.io.File f = new java.io.File(realPath);
        l.add(f);
        if(file.getDependOnCodeFiles() != null){
            String[] paths  = file.getDependOnCodeFiles().split(",");
            for (String codefile : paths) {

                StaticDocument file2 = libraryBusinessService.getFileByCodeType(codefile, productCode, productVersion);
                if((file2 != null)) {
                    l.add(new java.io.File(findRealPath(ec, file2.getPath())));
                }
            }
            downloadName = downloadName.substring(0,downloadName.lastIndexOf("."))+".zip";
        }
        InputStream pathStream = DownLoadHelper.getStreamAllFiles(l.toArray(new java.io.File[0]), downloadName);

        if (pathStream != null) {
            if(downloadName.indexOf('/')!=-1) {
                downloadName = downloadName.substring(downloadName.lastIndexOf('/')+1);
            }
            DownLoadHelper.downLoadFile(response, pathStream, downloadName);
        } else {
            logger.error("Le fichier " + realPath + " est introuvable!");
            throw new TechnicalException(CodeError.CODE_ERTEMO0001, null);
        }

    } else if (file.getAction().equals("open")) {
        final FacesContext ctx = FacesContext.getCurrentInstance();
        final ExternalContext extContext = ctx.getExternalContext();
        try {
            extContext.redirect(file.getPath());
        } catch (final IOException ioe) {
            throw new FacesException(ioe);

        }
    }
}

getStreamAllFiles

public static InputStream getStreamAllFiles(final File[] listDoc, String nameZIP) throws IOException {
    InputStream stream = null;
    if (listDoc != null) {
        if (listDoc.length == 1) {
            stream = new  ByteArrayInputStream(FileUtils.readFileToByteArray(listDoc[0]));
        } else if (listDoc.length > 1) {
            try( ByteArrayOutputStream baos = new ByteArrayOutputStream();ZipOutputStream zos = new ZipOutputStream(baos)){

                for (int i = 0; i < listDoc.length; i++) {

                    try(InputStream fis = new  ByteArrayInputStream(FileUtils.readFileToByteArray(listDoc[i]));BufferedInputStream bis = new BufferedInputStream(fis)){
                        zos.putNextEntry(new ZipEntry(listDoc[i].getName()));
                        byte[] bytes = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = bis.read(bytes)) != -1) {
                            zos.write(bytes, 0, bytesRead);
                        }
                    }
                }

                zos.closeEntry();

                stream = new ByteArrayInputStream(baos.toByteArray());
            }
        }
    }
    return stream;
}

downLoadFile

public static void downLoadFile(HttpServletResponse response,InputStream pathStream,String fileName) throws IOException {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + fileName);


    ServletOutputStream out = response.getOutputStream();
    IOUtils.copyLarge(pathStream, out);
    out.flush();
    FacesContext.getCurrentInstance().responseComplete();
    IOUtils.closeQuietly(pathStream);
    IOUtils.closeQuietly(out);

}

I have this error when trying to open the zip file

enter image description here

Petesh :

I presume you're trying to make a zip file with multiple files. The issues are in your getStreamAllFiles method as you don't close the zip entry after putting the content of the file, and you don't close the ZipOutputStream and the end of the loop, so the file loop should look like:

for (int i = 0; i < listDoc.length; i++) {

    try(InputStream fis = new  ByteArrayInputStream(FileUtils.readFileToByteArray(listDoc[i]));BufferedInputStream bis = new BufferedInputStream(fis)){
        zos.putNextEntry(new ZipEntry(listDoc[i].getName()));
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = bis.read(bytes)) != -1) {
            zos.write(bytes, 0, bytesRead);
        }
        zos.closeEntry();
    }
}
zos.close();
stream = new ByteArrayInputStream(baos.toByteArray());

i.e. move the zos.closeEntry() inside the loop through the files.

Without moving it inside the listDoc.length loop, if you have more than one file you will not be closing the ZipEntry properly at the end of each entry. You also need to issue a close() on the ZipOutputStream, as otherwise it will not write the end-of-zip directory (which is shown as an error End-of-central-directory signature not found if you test the file under a command line tool.

In addition, I'd move the allocation of the byte buffer outside the file loop as you only need to allocate it once, and reuse the same buffer for all the files you're writing.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Partial keyword match not working when I am trying to create a new column from a pandas data frame in python?

I am new to golang, I am trying to create a zip that must have a folder inside that is: tosend.zip/archivos/file.png

Why am I getting a Connection Error When Trying to Create a New SQL Server Database?

Why am I getting a "destination path '.' already exists" error when trying clone from my webfaction server?

Why am I receiving an error when trying to create the database by the URL of "jdbc:h2:test"

I am getting following error when i was trying run Angular 7 code on stackblitz from github repo

When I am trying to create a pipeline in amazon elastic transcoder using amazon console with IAM it gives me an error

Why I am getting an error when trying to create an audience?

I am getting an error when trying to get information from the database

I am getting NAN error when trying to retrieve a value from a class?

My Create storage is disabled when I am trying persisting files in Azure Cloud Shell

i am trying to create a geofence from the web browser and created a dynamic marker which gives an alert when crossed

Why am I getting this "unauthorized" error when trying to mirror OKD installation images from Quay.io?

Error when trying to extract files from a zip file

Error when i am trying to remove an element

In Swift, Why am I getting an error when trying to covert from a string to a date?

I am using elasticserach-1.4.1 and when I'm trying to create an index, I am getting the following error

I am trying to create a test label from Shippo, however I get a rate error

I am trying to create a socket in python 3 but i get this error, even when i copy code stragte from the web

Why am I getting a type error when trying to use a struct from a header in my .c file?

I get an error when I am trying to create a table and I can't figure why

I am trying to rename multiple files programmatically but when i run code it deletes all files from given folder

Why am I getting a syntax error when trying to create a table?

Why am I getting this error "TypeError: string indices must be integers" when trying to fetch data from an api?

Memory allocation error when trying to create a large zip file in memory

I am trying to create a subscription but an error occurs

I am getting a type error when I am trying to replace

Why am I getting error 42001-214 when trying to create a table in H2 database?

Error when trying to create a list of files