Search code examples
javaprintingzipinputstream

Capture InputStream character pattern and assign following characters to String


I have a program that needs to read for a specific line/characters in a file "FileToRead". The file is in a File.trk that when gets converted to File.zip has additional folders and files.

( File.trk to File.zip, File.zip structure is File.zip / FolderA / FolderB / FileToRead )

So far I have been able to convert File.trk to File.zip and have made it into FileToRead using ZipEntry and InputStream. My only problem now is how to capture a specific line or pattern of characters from the InputStream and assign following characters to String? Or is there a more efficient way of reading a file in a .zip folder with multi directories?

I know the contents of FileToRead and there is a specific line I soley need that contains a word (set of characters) only once.

Line in file: ["DictKey_sortie_29"] = "Gauntlet"
Word in file that only shows up once and will always be the same: "sortie"
Would like to set "Gauntlet" to String variable. ("Gauntlet" will always change to other name.)

    File trk = new File("C:\\Path\\File.trk");
    File zip = new File("C:\\Path\\File.zip");
    boolean success = trk.renameTo(zip);
    if (success) {
        ZipFile zipFile = new ZipFile(zip);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while(entries.hasMoreElements()){                                           
            ZipEntry entry = entries.nextElement();                                                                                                    
            if (entry.getName().contentEquals("FolderA/FolderB/FileToRead")) {
                InputStream stream = zipFile.getInputStream(entry);                    
                int content;
                while ((content = stream.read()) != -1) {
                    System.out.print((char)content);
                }
                stream.close();
            }
        }
    }

Solution

  • Wrap zipFile.getInputStream(entry) with InputStreamReader and BufferedReader, then read the file line-by-line.

    BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
    String line;
    while ((line = br.readLine()) != null) {
      if (line.contains("sortie")) {
        //do your thing here
      }
    }
    

    And don't forget to close the BufferedReader after you finished.