This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Convert an InputStream to a byte array in Java

How to read the entire InputStream into a byte array?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

You can use Apache Commons IO to handle this and similar tasks.

This IOUtils type has static methods to read InputStream and return byte[].

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
Copy the code

Internally, this creates a ByteArrayOutputStream and copies the bytes into the output, then calls toByteArray(). It processes large files by copying bytes from a 4KiB block.

Answer:

Java 9 will finally give you a nice way to:

InputStream in = ... ; ByteArrayOutputStream bos = new ByteArrayOutputStream(); in.transferTo( bos ); byte[] bytes = bos.toByteArray();Copy the code

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 1…

The author suggests: in the translationHow to convert a string to an InputStream in Java? 和 How do I read/convert an input stream to a string in Java?I realized that it must have something to do with ByteArrayOutputStream, and of course when I learned that ByteArrayOutputStream was performing pretty well, I realized thatRead plain text files in Java? recommendedThis translation is about this FileChannel thing

As you can see, The Performance of FileChannel is relatively high. Briefly, take rocketMQ, which is a popular file system for storing data, producing and consuming data as directly manipulated files, It involves page caching, FileChannel, and FileChannel reading a page of 4KB data at a time. High performance benefits from ByteBuffer buffers, MMAP memory maps, and RokcetMQ tuning for better performance

Preallocate MappedFile mlock System call file preheat sequential read and sequential write

I’m just doing a piece here, everybody come on!


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️