根据从C#写入文件的方式,两个相同的文件具有不同的文件大小
我正在尝试将序列化为JSON格式的对象数组写入文件。我正在尝试以两种不同的方式编写它,如下所示。
I am trying to write to a file an array of object serialised into JSON format. I am trying to write it in two different way as shown below.
ToSerialise[] Obj = new ToSerialise[10];
for (int i = 0; i < 10; i++)
{
Obj[i] = new ToSerialise();
}
//First form of serialising
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String SerialisedOutput;
SerialisedOutput = JsonConvert.SerializeObject(Obj, Formatting.Indented);
FileStream fs1 = new FileStream(@"C:\file1.log", FileMode.CreateNew);
fs1.Write(uniEncoding.GetBytes(SerialisedOutput), 0, uniEncoding.GetByteCount(SerialisedOutput));
fs1.Close();
//Second form of serialising
FileStream fs2 = new FileStream(@"C:\file2.log", FileMode.CreateNew);
StreamWriter sw = new StreamWriter(fs2);
JsonWriter jw = new JsonTextWriter(sw);
JsonSerializer js = new JsonSerializer();
jw.Formatting = Formatting.Indented;
js.Serialize(jw, Obj);
jw.Close();
fs2.Close();
即使两个文件的内容相同,它们的文件大小也不同。实际上,第一个文件恰好是第二个文件的两倍。我尝试使用textpad比较输出,并说它们完全一样。为什么它们的文件大小不同?
Even though the content of both the files are same, they have different file size. Actually the first file is exactly twice the size of the second file. I tried comparing the output using textpad and it says they are excatly the same. Why do they have different file size?
我在Windows 7 32位.Net4上运行此文件
I am running this on Windows 7 32 bit, .Net4
谢谢
即使两个文件的内容相同,它们的文件大小也不同。
Even though the content of both the files are same, they have different file size.
如果它们的大小不同,则它们肯定地具有不同的内容。一个文件(几乎)只是一个字节序列-如果两个序列的长度不同,它们就是不同的序列。
If they have a different size, then they definitely have different contents. A file is (pretty much) just a sequence of bytes - and if two sequences have different lengths, they're different sequences.
在这种情况下,两个文件都表示相同的 text ,但是使用不同的编码- file2
将使用UTF-8,而 file1
将使用UTF-16。
In this case, the two files both represent the same text, but using different encodings - file2
will use UTF-8, and file1
will use UTF-16.
以另一种方式思考:如果将同一张图片保存到两个文件(一个为JPEG和一个为PNG),则会您希望文件大小相同吗?
To think of it a different way: if you saved the same picture to two files, one as JPEG and one as PNG, would you expect the files to be the same size?