Поврежденный ZIp генерируется в Java - PullRequest
0 голосов
/ 27 апреля 2020

Я написал фрагмент кода, чтобы записать мои файлы в zip-файл и поместить его на сервер. Теперь файл (zip) успешно создан. Но он поврежден и не открывается. Я проверил inte rnet для различных решений, таких как закрытие потоков и ZipOutputStream flu sh, но ничего не помогло.

Пожалуйста, помогите!

    // Function to write files in ZIP archive..
    public void writeToZip( String ibftDirectory ) throws Exception {

        byte[] buffer = new byte[1024];

        File file = new File(ibftDirectory);
        String zipFileName = file.getName().replace(".csv",".zip");

        try {
            LOGGER.println( "1" );
            FileOutputStream fos = new FileOutputStream(ibftDirectory.replace( ".csv",".zip"));
            LOGGER.println( fos.toString() );
            ZipOutputStream zos = new ZipOutputStream(fos);
            LOGGER.println( zos.toString() );
            zos.putNextEntry(new ZipEntry(file.getName()));
            LOGGER.println( "2" );
            FileInputStream in = new FileInputStream( ibftDirectory );
            LOGGER.println( in.toString() );
            int len;
            while ((len = in.read(buffer)) > 0) {
                LOGGER.println( "value " + len );
                zos.write(buffer, 0, len);
                LOGGER.println( "3" );
            }
            in.close();
            LOGGER.println( "4" );
            zos.finish();
            zos.flush();
            zos.closeEntry();
            LOGGER.println( "5" );
            zos.close();
            fos.close();
            LOGGER.println( "6" );

                } catch (FileNotFoundException ex) {
                    System.err.format("The file %s does not exist", ibftDirectory);
                } catch (IOException ex) {
                    System.err.println("I/O error: " + ex);
                }
     finally {

     }

           }

ibftdirectorypath = / dev /files/myfile.key

1 Ответ

0 голосов
/ 27 апреля 2020

Вы создаете своего рода рекурсию, помещая сам файл как ZipEntry.

Можете ли вы попробовать этот код:

public static void writeToZip(String ibftDirectory) throws Exception {

    try (FileInputStream fis = new FileInputStream(ibftDirectory);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ibftDirectory + ".zip"))) {
        zos.putNextEntry(new ZipEntry(ibftDirectory.substring(ibftDirectory.indexOf(File.separator) + 1)));
        int len;
        byte[] buffer = new byte[1024];
        while ((len = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
        zos.closeEntry();
    }
}

С синтаксисом try-with-resource вы управлять всеми операциями открытия и закрытия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...