Читать поток дважды - PullRequest
       7

Читать поток дважды

105 голосов
/ 29 февраля 2012

Как вы читаете один и тот же входной поток дважды?Можно ли это как-то скопировать?

Мне нужно получить изображение из Интернета, сохранить его локально, а затем вернуть сохраненное изображение.Я просто подумал, что будет быстрее использовать тот же поток вместо того, чтобы начинать новый поток для загруженного контента, а затем читать его снова.

Ответы [ 9 ]

93 голосов
/ 29 февраля 2012

Вы можете использовать org.apache.commons.io.IOUtils.copy, чтобы скопировать содержимое InputStream в байтовый массив, а затем многократно читать из байтового массива, используя ByteArrayInputStream. E.g.:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(in, baos);
byte[] bytes = baos.toByteArray();

// either
while (needToReadAgain) {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    yourReadMethodHere(bais);
}

// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
    bais.reset();
    yourReadMethodHere(bais);
}
24 голосов
/ 29 февраля 2012

В зависимости от того, откуда поступает InputStream, вы не сможете сбросить его. Вы можете проверить, поддерживаются ли mark() и reset(), используя markSupported().

Если это так, вы можете вызвать reset() для InputStream, чтобы вернуться в начало. Если нет, вам нужно снова прочитать InputStream из источника.

9 голосов
/ 29 января 2014

если ваша InputStream поддерживает использование метки, тогда вы можете mark() ваш inputStream и затем reset() его.если ваш InputStrem не поддерживает метку, вы можете использовать класс java.io.BufferedInputStream, поэтому вы можете встроить свой поток в BufferedInputStream, например,

    InputStream bufferdInputStream = new BufferedInputStream(yourInputStream);
    bufferdInputStream.mark(some_value);
    //read your bufferdInputStream 
    bufferdInputStream.reset();
    //read it again
7 голосов
/ 25 мая 2015

Вы можете обернуть входной поток с помощью PushbackInputStream. PushbackInputStream позволяет непрочитанных (" write back ") байтов, которые уже были прочитаны, поэтому вы можете сделать так:

public class StreamTest {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's wrap it with PushBackInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    ((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3


  }

  private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
    System.out.print("Reading stream: ");

    byte[] buf = new byte[howManyBytes];

    int next = 0;
    for (int i = 0; i < howManyBytes; i++) {
      next = is.read();
      if (next > 0) {
        buf[i] = (byte) next;
      }
    }
    return buf;
  }

  private static void printBytes(byte[] buffer) throws IOException {
    System.out.print("Reading stream: ");

    for (int i = 0; i < buffer.length; i++) {
      System.out.print(buffer[i] + " ");
    }
    System.out.println();
  }


}

Обратите внимание, что PushbackInputStream хранит внутренний буфер байтов, поэтому он действительно создает буфер в памяти, в котором хранятся байты с обратной записью.

Зная этот подход, мы можем пойти дальше и объединить его с FilterInputStream. FilterInputStream хранит исходный поток ввода в качестве делегата. Это позволяет создать новое определение класса, которое позволяет автоматически " unread " исходные данные. Определение этого класса следующее:

public class TryReadInputStream extends FilterInputStream {
  private final int maxPushbackBufferSize;

  /**
  * Creates a <code>FilterInputStream</code>
  * by assigning the  argument <code>in</code>
  * to the field <code>this.in</code> so as
  * to remember it for later use.
  *
  * @param in the underlying input stream, or <code>null</code> if
  *           this instance is to be created without an underlying stream.
  */
  public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
    super(new PushbackInputStream(in, maxPushbackBufferSize));
    this.maxPushbackBufferSize = maxPushbackBufferSize;
  }

  /**
   * Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
   * in the stream
   *
   * @param buffer the destination buffer to which read the data
   * @param offset  the start offset in the destination <code>buffer</code>
   * @aram length how many bytes to read from the stream to buff. Length needs to be less than
   *        <code>maxPushbackBufferSize</code> or IOException will be thrown
   *
   * @return number of bytes read
   * @throws java.io.IOException in case length is
   */
  public int tryRead(byte[] buffer, int offset, int length) throws IOException {
    validateMaxLength(length);

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int bytesRead = 0;

    int nextByte = 0;

    for (int i = 0; (i < length) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        buffer[offset + bytesRead++] = (byte) nextByte;
      }
    }

    if (bytesRead > 0) {
      ((PushbackInputStream) in).unread(buffer, offset, bytesRead);
    }

    return bytesRead;

  }

  public byte[] tryRead(int maxBytesToRead) throws IOException {
    validateMaxLength(maxBytesToRead);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int nextByte = 0;

    for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        baos.write((byte) nextByte);
      }
    }

    byte[] buffer = baos.toByteArray();

    if (buffer.length > 0) {
      ((PushbackInputStream) in).unread(buffer, 0, buffer.length);
    }

    return buffer;

  }

  private void validateMaxLength(int length) throws IOException {
    if (length > maxPushbackBufferSize) {
      throw new IOException(
        "Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
        length);
    }
  }

}

Этот класс имеет два метода. Один для чтения в существующий буфер (определение аналогично вызову public int read(byte b[], int off, int len) класса InputStream). Второй, который возвращает новый буфер (это может быть более эффективно, если размер буфера для чтения неизвестен).

Теперь давайте посмотрим на наш класс в действии:

public class StreamTest2 {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's use our TryReadInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new TryReadInputStream(originalStream, 10);

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
    printBytes(readBytes); // prints 1 2 3

    // we can also call normal read which will actually read the bytes without "writing them back"
    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 4 5 6

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
    printBytes(readBytes); // prints 7 8 9

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 7 8 9


  }



}
4 голосов
/ 29 февраля 2012

Если вы используете реализацию InputStream, вы можете проверить результат InputStream#markSupported(), который скажет вам, можете ли вы использовать метод mark() / reset().

Если вы можете пометить поток при чтении, тогда позвоните reset(), чтобы вернуться к началу.

Если вы не можете, вам придется снова открыть поток.

Другим решением было бы преобразование InputStream в байтовый массив, а затем итерация по массиву столько раз, сколько вам нужно. В этом посте вы можете найти несколько решений Конвертировать InputStream в байтовый массив в Java , используя сторонние библиотеки или нет. Внимание, если прочитанное содержимое слишком большое, у вас могут возникнуть проблемы с памятью.

Наконец, если вам нужно прочитать изображение, используйте:

BufferedImage image = ImageIO.read(new URL("http://www.example.com/images/toto.jpg"));

Использование ImageIO#read(java.net.URL) также позволяет использовать кэш.

2 голосов
/ 04 июня 2017

Как насчет:

if (stream.markSupported() == false) {

        // lets replace the stream object
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(stream, baos);
        stream.close();
        stream = new ByteArrayInputStream(baos.toByteArray());
        // now the stream should support 'mark' and 'reset'

    }
2 голосов
/ 29 февраля 2012

Преобразуйте входной поток в байты, а затем передайте его в функцию savefile, где вы собираете его в входной поток.Также в исходной функции используйте байты для других задач

0 голосов
/ 28 апреля 2019

Для разделения InputStream на две части, , избегая при этом загрузки всех данных в память и последующей их обработки независимо:

  1. Создание пары OutputStream,точно: PipedOutputStream
  2. Соедините каждый PipedOutputStream с PipedInputStream, эти PipedInputStream являются возвращаемыми InputStream.
  3. Соедините источник InputStream с только что созданным OutputStream.Итак, все, что читается из источника InputStream, будет записано в обоих OutputStream.Нет необходимости реализовывать это, потому что это уже сделано в TeeInputStream (commons.io).
  4. В отдельном потоке прочитайте весь источник inputStream и неявно передайте входные данные вцелевой inputStreams.

    public static final List<InputStream> splitInputStream(InputStream input) 
        throws IOException 
    { 
        Objects.requireNonNull(input);      
    
        PipedOutputStream pipedOut01 = new PipedOutputStream();
        PipedOutputStream pipedOut02 = new PipedOutputStream();
    
        List<InputStream> inputStreamList = new ArrayList<>();
        inputStreamList.add(new PipedInputStream(pipedOut01));
        inputStreamList.add(new PipedInputStream(pipedOut02));
    
        TeeOutputStream tout = new TeeOutputStream(pipedOut01, pipedOut02);
    
        TeeInputStream tin = new TeeInputStream(input, tout, true);
    
        Executors.newSingleThreadExecutor().submit(tin::readAllBytes);  
    
        return Collections.unmodifiableList(inputStreamList);
    }
    

Будьте внимательны, чтобы закрыть inputStreams после использования и закрыть поток, который выполняется: TeeInputStream.readAllBytes()

В случае, если вам нужно разделите его на кратные InputStream вместо двух.Замените в предыдущем фрагменте кода класс TeeOutputStream для вашей собственной реализации, который инкапсулирует List<OutputStream> и переопределит интерфейс OutputStream:

public final class TeeListOutputStream extends OutputStream {
    private final List<? extends OutputStream> branchList;

    public TeeListOutputStream(final List<? extends OutputStream> branchList) {
        Objects.requireNonNull(branchList);
        this.branchList = branchList;
    }

    @Override
    public synchronized void write(final int b) throws IOException {
        for (OutputStream branch : branchList) {
            branch.write(b);
        }
    }

    @Override
    public void flush() throws IOException {
        for (OutputStream branch : branchList) {
            branch.flush();
        }
    }

    @Override
    public void close() throws IOException {
        for (OutputStream branch : branchList) {
            branch.close();
        }
    }
}
0 голосов
/ 04 декабря 2018

Если кто-то работает в приложении Spring Boot и вы хотите прочитать тело ответа RestTemplate (именно поэтому я хочу прочитать поток дважды), есть чистый (э) способ это.

Прежде всего, вам необходимо использовать StreamUtils Spring для копирования потока в строку:

String text = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()))

Но это еще не все. Вам также нужно использовать фабрику запросов, которая может буферизовать поток для вас, например:

ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);

Или, если вы используете фабричный боб, то (это же Котлин, но тем не менее):

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun createRestTemplate(): RestTemplate = RestTemplateBuilder()
  .requestFactory { BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory()) }
  .additionalInterceptors(loggingInterceptor)
  .build()

Источник: https://objectpartners.com/2018/03/01/log-your-resttemplate-request-and-response-without-destroying-the-body/

...