0

**I have a folder with a few files and subdirectories which also have some files. But when I extract the zip file inside the Linux system using the following python code. instead of creating subdirectories, it creates files with names that contain subdirectory name with separator where that zip file I have created by the following code using java language in the window system.

Example: ABC.zip file which contains abc.txt, subfolder name ABCD and this ABCD folder contain one file name test.txt then in python when I extract, it creates two files with abc.txt, ABCD\text.txt names instead of ABCD folder and then inside ABCD text.txt file**

Python side code: To extract the zip file

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)

Java side code: To create the zip file

String srcDir = "E:\\tomcat\\ai_data\\3";
File file = new File(srcDir);

File desFile = new File(srcDir.concat(".zip"));

final Path sourceDir = Paths.get(srcDir);
String zipFileName = srcDir.concat(".zip");
try {
    final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
    
    Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
            try {
                Path targetFile = sourceDir.relativize(file);
                 
                outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                byte[] bytes = Files.readAllBytes(file);
                outputStream.write(bytes, 0, bytes.length);
                outputStream.flush();
                outputStream.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Create Zip file " + file.getFileName(), e.getMessage());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    outputStream.close();
} catch (IOException e) {}

1 Answer 1

1

The problem seems to be that the Java code is creating zip file entries using the Windows style of seperators ( \ ) then the python code is seeing that the file contains ( \ ) and believes to to be part of the name because it is expecting ( / ) as path seperators. If the java code is always going to create a zip file that is to be extracted on a linux system try converting the filepath of the zip entry to use Linux seperators e.g. :

Path targetFile = sourceDir.relativize(file);

//Convert seperators to Linux Style
String linuxStylePath = FilenameUtils.seperatorsToUnix(targetFile.toString());   

outputStream.putNextEntry(new ZipEntry(linuxStylePath));

Reference Apache Commons IO Library to do the path conversions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.