kanishka malpana
kanishka malpana

Reputation: 21

Reading data from a file inside a zip file in java without extracting the Zip

enter image description here

I need to read a file inside a zip folder without extracting Zip the zip folder then I need to keep all the data in that file in a buffer.

public static void getLogBuffers(String path) throws IOException
{
    String zipFileName = path;
    String destDirectory = path + "/..";

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));
    ZipEntry zipEntry = zis.getNextEntry();
    boolean isErrorLogFileExist = false;
    boolean isWindowLogFileExist = false;
    BufferedInputStream errorLogBuffer = null;
    BufferedInputStream windowLogBuffer = null;
    while (zipEntry != null)
    {
      String filePath = zipFileName + "/" + zipEntry.getName();
      System.out.println("unzipping" + filePath);
      if (!zipEntry.isDirectory())
      {
        //FileOutputStream fos = new FileOutputStream(filePath);
        if (zipEntry.getName().endsWith("errorlog.txt"))
        {
          isErrorLogFileExist = true;
          errorLogBuffer = new BufferedInputStream(new FileInputStream(filePath));
          for (int i = errorLogBuffer.read(); i != -1; i = errorLogBuffer.read())
          {
            errorLogBuffer = new BufferedInputStream(new FileInputStream(filePath));
          }
        }

FileNotFoundException is thrown in line

errorLogBuffer = new BufferedInputStream(new FileInputStream(filePath));

  Exception in thread "main" java.io.FileNotFoundException: C:\issues\log.zip\log\errorlog.txt (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at errorWindowLogMapper.unZipFile(errorWindowLogMapper.java:113)
at errorWindowLogMapper.main(errorWindowLogMapper.java:38)

appreciate if anyone can help

Upvotes: 1

Views: 1034

Answers (1)

Eyal Sooliman
Eyal Sooliman

Reputation: 2268

Try this code:

        ZipFile zipFile = new ZipFile(new File(zipPath));
        List<String> filesList = new ArrayList<>();
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        ZipEntry entry = null;
        StringBuilder out = null;
        while (entries.hasMoreElements()) 
       {
            entry = entries.nextElement();
            StringBuilder out = new StringBuilder();
            BufferedReader reader = new BufferedReader(new 
            InputStreamReader(in));
            String line;
                     while ((line = reader.readLine()) != null) 
                        {
                            out.append(line);
                        }
       }
       return out.toString();

Upvotes: 0

Related Questions