There is a code in which to create a copy of the stream. I have never faced a similar task before.
The fact is that I need to analyze this flow, and only then read it. I post the problem piece of code:

import java.io.*; import java.nio.charset.Charset; import java.util.Scanner; import java.util.jar.JarFile; import java.util.zip.*; public class InputZip{ private ZipEntry entry; private ZipInputStream zipInput; public InputZip(String zipName) throws IOException { zipInput = new ZipInputStream(new FileInputStream(zipName), Charset.defaultCharset()); while ((entry = zipInput.getNextEntry()) != null) { InputStreamReader in = new InputStreamReader(zipInput); InputStreamReader in2 = new InputStreamReader(zipInput); // Бесполезный InputStreamReader in3 = new InputStreamReader(zipInput);// Бесполезный analiz(in); Scanner scan = new Scanner(zipInput); String s = scan.nextLine(); // Исключение! Поток уже использован :( zipInput.closeEntry(); } zipInput.close(); } private void analiz(InputStreamReader b) throws IOException { //Анализ потока (полное прочтение) } } 

Need to get a copy of zipInput .

  • give me all the code ( ideone.com ) - Vladislav Kuznetsov

3 answers 3

InputStreamReader is designed so that you can only read from it once. If the data needs to be processed twice, then it is better to use the BufferedReader or read the data into an array and form a couple of threads reading from it.

UPDATE: A primitive example of re-reading from a buffered stream

 import java.io.*; public class Main { private static boolean analyze(BufferedReader br) throws IOException { br.mark(1000); String line = br.readLine(); if(line != null) { System.out.println(line); br.reset(); return true; } else { return false; } } public static void main(final String args[]) throws IOException { BufferedReader br = new BufferedReader(new FileReader("test.txt")); if(analyze(br)) System.out.println(br.readLine()); else System.err.println("ERROR!"); } } 
  • Can you please an example with BufferedReader - sair
  • @sair updated the answer. - Sergey Gornostaev

Well, you get an object that refers to the file inside, but you still read the zip file itself. Use this method:

  InputStream is = zip.getInputStream(entry); InputStreamReader isr = new InputStreamReader(is); 

Here is an example.

    It is possible for your stream analysis task to do an analysis instead of stream copying during processing. Look in the direction of FilterInputStream, the essence is in redefining the methods inputStream to which you add the analysis you need.

    • I would give everything to do everything at once, but if the analysis gives the wrong result, the second stream will already know about it and will do everything right ... I have solved this problem by simply creating a file with the values ​​of this stream and after opening two FileInputStream I decide everything ... but this is a very resource-intensive version of this. I’m interested in the suggestion of Sergey Gornostaev - sair