I often run into the problem that I have one stream full of data and want to write everything of it into another stream.
All code-examples out there use a buffer in form of a byte-array.
Is there a more elegant way to this?
If not, what's the ideal size of the buffer. Which factors make up this value?
CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.
Among these, you can read the contents of a file using Scanner, BufferedReader and, FileReader classes. In the same way, you can write data into a file using BufferedWriter, FileOutputStream, FileWriter.
This is entirely possible, no problem; but you wouldn't use the same stream, you would use two different ones, and pipe data from the input to the output in a loop.
As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.
In .NET 4.0 we finally got a Stream.CopyTo
method! Yay!
Regarding the ideal buffer size:
"When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes)."
Any stream-reading process will use Read(char buffer[], int index, count), which is the method this quote refers to.
http://msdn.microsoft.com/en-us/library/9kstw824.aspx (Under "Remarks").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With