Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to copy inputstream streams

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report