Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Java to copy inputstream streams

Shulou Source: shulou.com Published: 2022-06-03 09:44:19 09月16日 Update

This article is about how to use Java to replicate inputstream streams. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

After you get an inputstream, you may have to use it multiple times to perform read operations. Since the stream can't be read once, and the InputStream object itself cannot be copied, and it doesn't implement the Cloneable interface, something has to be done.

The idea of realization is:

1. Convert InputStream to ByteArrayOutputStream first

2. Convert back from ByteArrayOutputStream when you want to use the InputStream object later.

Code

Package com.test;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;public class StreamOperateUtil {public static void main (String [] args) throws FileNotFoundException {InputStream input = new FileInputStream ("c:\ test.txt"); / / InputStream input = httpconn.getInputStream (); / / you can write the stream ByteArrayOutputStream baos = cloneInputStream (input) you got here. / / Open two new input streams InputStream stream1 = new ByteArrayInputStream (baos.toByteArray ()); InputStream stream2 = new ByteArrayInputStream (baos.toByteArray ());} private static ByteArrayOutputStream cloneInputStream (InputStream input) {try {ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len;while ((len = input.read (buffer)) >-1) {baos.write (buffer, 0, len);} baos.flush (); return baos;} catch (IOException e) {e.printStackTrace (); return null Thank you for your reading! On "how to use Java to achieve inputstream stream replication" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!

Tags: Content object more article good practical two code method idea interface article look knowledge reference help related input Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei MariaDB NVidia Linux Microsoft