This means that you are creating a new object, and more importantly, a new byte array which is used as buffer inside the BufferedInputStream. This can put pressure on the Java garbage collector, if the number of files or streams read is high, and if they are read quickly after each other.
An alternative is to create a reusable BufferedInputStream where you can replace the underlying source InputStream , so the BufferedInputStream and its internal byte array buffer can be reused. To save you the trouble, I have created such a ReusableBufferedInputStream , and included the code for it further down this tutorial. First you need to create a ReusableBufferedInputStream. Here is an example of how to create a ReusableBufferedInputStream :. When you have created a ReusableBufferedInputStream you need to set the InputStream on it to use as underlying data source.
The setSource method actually returns a reference to the ReusableBufferedInputStream , so you can actually create a ReusableBufferedInputStream and set the source in a single instruction:.
When you are done using the ReusableBufferedInputStream you need to close it. Closing it will only close the underlying source InputStream. Here is how it looks to reuse a ReusableBufferedInputStream :. Here is the code for the ReusableBufferedInputStream described above.
Note, that this implementation only overrides the read method of the InputStream class that it extends. The rest of the InputStream methods have been left out to keep the code shorter - but you can implement them yourself in case you need them.
Tutorials About RSS. Java IO. Optimal Buffer Size for a BufferedInputStream You should make some experiments with different buffer sizes to find out which buffer size seems to give you the best performance on your concrete hardware.
IOException; import java. Tweet Jakob Jenkov. Featured Videos Sponsored Ads. All Trails. Trail TOC. Page TOC. Try one of the many quizzes. More than Java questions with detailed answers. Yes, I want to learn Java quickly. You may also like. Java String Array Length Example. Convert java int to Integer object Example. List Even Numbers Java Example. Draw Smiley In Applet Example. List Odd Numbers Java Example. For example,. When we run the program, the file flush.
To close the buffered output stream, we can use the close method. Once the method is called, we cannot use the output stream to write the data. Course Index Explore Programiz. Java for Loop. Arrays in Java. Interfaces in Java. Java ArrayList. Popular Examples Check prime number. Print the Fibonacci series. Print Pyramids and Patterns. Multiply two matrices. Find the standard deviation. Reference Materials String. Start Learning Java.
0コメント