what's the difference between a streamwriter and a binarywriter?
this really confuses me, say i want to save an integer into a file, int x=56, the binarywriter takes the ascii equivalent of the re开发者_StackOverflow社区presentation of 56 in memory 00000000 00000000 00000000 00111000 , which would be : null null null 8 and write it to the file? am i correct? can someone explain how those twofunction and when should i use each of them? im using c# btw. thanx in advance!
From the MSDN pages for StreamWriter and BinaryWriter you can clearly see the differences:
StreamWriter:
Implements a TextWriter for writing characters to a stream in a particular encoding.
And:
BinaryWriter:
Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
The first one writes things as text, the second writes in binary, little endian, so int x = 56
would be written 00111000 00000000 00000000 00000000
.
The binary writer writes the in-memory binary representation of the integer. The stream writer writes the ASCII representation. Generally speaking, the former can be more compact and efficient (consider writing the integer 23861398 - the binary writer would require 4 bytes, but the stream writer would require 8, 16, or even 32 depending on the encoding) but the latter results in plain old text.
From what I can discern... StreamWriter is more for text and BinaryWriter is for primitive types including strings of particular encodings. Saying that the BinaryWriter writes in binary though is kind of misleading to people who take things at face value... as I did. I assumed that when I write an integer to the underlying stream it would actually write it in binary and I could read it again as a stream of 1's and 0's. To put things down as it looks in code:
MemoryStream stream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(35);
// is equivalent to doing:
stream.Write(BitConverter.GetBytes((int)35), 0, 4);
Though the BinaryWriter uses bit shifting to extract the bytes and BitConverter uses unsafe pointer casting, the result is the same. An int is 32 bits or 4 bytes in length, and all it simply does is writes the bytes that represent that int to it's underlying stream.
StreamWriter does the same thing only that it's meant for text, so integers won't be converted to bytes, but instead to chars... this is similar to writing:
byte[] buffer = Encoding.UTF8.GetBytes("my string here 1234");
stream.Write(buffer, 0, buffer.Length);
That is why I said it's misleading to say it writes in binary.. because it does.. technically. Break down each written byte into bits and you get the binary values. However it would make more sense to say that it writes primitive types as byte arrays. If you were to convert the stream to a string you would not get a string of 1's and 0's.
StreamWriter
is for text and BinaryWriter
writes the actual binary representation of what you want to write. I'm not 100 % sure, but almost :).
精彩评论