[英]How to read int array from binary file c#
我有以下代码:
LZW lzw = new LZW();
int[] a = lzw.Encode(imageBytes);
FileStream fs = new FileStream("image-text-16.txt", FileMode.Append);
BinaryWriter w = new BinaryWriter(fs);
for (int i = 0; i < a.Length; i++)
{
w.Write(a[i]);
}
w.Close();
fs.Close();
如何从文件中读取数组元素? 我尝试了几种方法。 例如,我将数组的长度写入文件,然后尝试读取该数字。 但是,我失败了。
注意。 我需要获取int数组。
您在寻找这个吗?
var bytes = File.ReadAllBytes(@"yourpathtofile");
或更多类似的东西:
using (var filestream = File.Open(@"C:\apps\test.txt", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
for (var i = 0; i < arraysize; i++)
{
Console.WriteLine(binaryStream.ReadInt32());
}
}
或者,一个带有单元测试的小例子:
创建一个带有整数的二进制文件...
[Test]
public void WriteToBinaryFile()
{
var ints = new[] {1, 2, 3, 4, 5, 6, 7};
using (var filestream = File.Create(@"c:\apps\test.bin"))
using (var binarystream = new BinaryWriter(filestream))
{
foreach (var i in ints)
{
binarystream.Write(i);
}
}
}
还有一个读取二进制文件的小示例测试
[Test]
public void ReadFromBinaryFile()
{
// Approach one
using (var filestream = File.Open(@"C:\apps\test.bin", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
var pos = 0;
var length = (int)binaryStream.BaseStream.Length;
while (pos < length)
{
var integerFromFile = binaryStream.ReadInt32();
pos += sizeof(int);
}
}
}
从二进制文件读取的另一种方法
[Test]
public void ReadFromBinaryFile2()
{
// Approach two
using (var filestream = File.Open(@"C:\apps\test.bin", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
while (binaryStream.PeekChar() != -1)
{
var integerFromFile = binaryStream.ReadInt32();
}
}
}
我会反过来说。 唯一的事情是您在阅读尺寸之前不知道尺寸,因此请先进行计算。 哦,我会使用“使用”来确保正确处置(并关闭)物件:
int[] ll;
using (FileStream fs = File.OpenRead("image-text-16.txt"))
{
int numberEntries = fs.Length / sizeof(int);
using (BinaryReader br = new BinaryReader(fs))
{
ll = new int[numberEntries];
for (int i = 0; i < numberEntries; ++i)
{
ll[i] = br.ReadInt32();
}
}
}
// ll is the result
我不太了解的是为什么要从LZW编写int [],但是我想这是有原因的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.