Read directly a file within a Zip file - Java

后端 未结 3 1898
一个人的身影
一个人的身影 2020-12-19 12:31

My situation is that I have a zip file that contains some files (txt, png, ...) and I want to read it directly by their names, I have tested the following code but no result

3条回答
  •  感动是毒
    2020-12-19 13:14

    Your current approach is definitely not going to work. You made up an arbitrary 'access' scheme and used it in a class that has no idea what you are trying to do. What you can do is use a ZipInputStream to read the entry you are looking for:

    URL zipFileURL = Thread.currentThread().getContextClassLoader().getResource("zipfile.zip");
    InputStream inputStream = zipFileURL.openStream();
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    
    ZipEntry zipEntry = null;
    
    do {
        zipEntry = zipInputStream.getNextEntry();
        if(zipEntry == null) break;
    }
    while(zipEntry != null && (! "textfile".equals(zipEntry.getName()));
    
    if(zipEntry != null ) {
        // do some stuff
    }
    

    This is adhoc code, fix it up to do what you need. Also, there might be some more efficient classes to handle Zip files, for example in the Apache Commons IO library.

提交回复
热议问题