【发布时间】:2011-06-21 03:38:18
【问题描述】:
假设只有一个双精度值以二进制格式写入文件。如何使用 C# 或 Java 读取该值?
如果我必须从一个巨大的二进制文件中找到一个双精度值,我应该使用什么技术来找到它?
【问题讨论】:
标签: c# .net c#-4.0 bitconverter
假设只有一个双精度值以二进制格式写入文件。如何使用 C# 或 Java 读取该值?
如果我必须从一个巨大的二进制文件中找到一个双精度值,我应该使用什么技术来找到它?
【问题讨论】:
标签: c# .net c#-4.0 bitconverter
Double 是 8 个字节。要从二进制文件中读取单个双精度,您可以使用 BitConverter 类:
var fileContent = File.ReadAllBytes("C:\\1.bin");
double value = BitConverter.ToDouble(fileContent, 0);
如果需要从文件中间读取double,请将0替换为字节偏移量。
如果不知道偏移量,就无法判断字节数组中的某个值是双精度、整数还是字符串。
另一种方法是:
using (var fileStream = File.OpenRead("C:\\1.bin"))
using (var binaryReader = new BinaryReader(fileStream))
{
// fileStream.Seek(0, SeekOrigin.Begin); // uncomment this line and set offset if the double is in the middle of the file
var value = binaryReader.ReadDouble();
}
第二种方法更适合大文件,因为它不会将整个文件内容加载到内存中。
【讨论】:
您可以使用BinaryReader 类。
double value;
using( Stream stream = File.OpenRead(fileName) )
using( BinaryReader reader = new BinaryReader(stream) )
{
value = reader.ReadDouble();
}
对于第二点,如果您知道偏移量,只需使用Stream.Seek 方法即可。
【讨论】:
似乎我们需要知道双精度值是如何在文件中编码的,然后才能找到它。
【讨论】:
1)
double theDouble;
using (Stream sr = new FileStream(@"C:\delme.dat", FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[8];
sr.Read(buffer, 0, 8);
theDouble = BitConverter.ToDouble(buffer, 0);
}
2) 你不能。
【讨论】:
以下是如何读取(以及出于测试目的写入)双精度数:
// Write Double
FileStream FS = new FileStream(@"C:\Test.bin", FileMode.Create);
BinaryWriter BW = new BinaryWriter(FS);
double Data = 123.456;
BW.Write(Data);
BW.Close();
// Read Double
FS = new FileStream(@"C:\Test.bin", FileMode.Open);
BinaryReader BR = new BinaryReader(FS);
Data = BR.ReadDouble();
BR.Close();
从大文件中取出数据取决于文件中数据的布局方式。
【讨论】:
using 块而不是仅仅调用Close。
using 关键字绝对属于该类别。另外,恕我直言 using 在这种情况下实际上使代码更简单。
using (FileStream filestream = new FileStream(filename, FileMode.Open))
using (BinaryReader reader = new BinaryReader(filestream))
{
float x = reader.ReadSingle();
}
【讨论】: