对于一个类似VBF文件中有ASCII+二进制俩种编码方式的文件的读取
思路:对于二进制编码的用BinaryReader。因为二进制编码的数据我要得到的也是byte[]就不用二次转了,重点就是如何判断指针的初始位置。
//对于一行一行的
public void parseHead(string path)
{
StreamReader sr = new StreamReader(path);
int i = 0;
while (true)
{
szLine = sr.ReadLine(); //读取一行数据
if (szLine == null) //读完所有行
{
break;
}
}
}
private void getPosition()
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
MaxPosition=fs.Length;//记录全部的长度
byte[] buffer = new byte[512];
fs.Read(buffer, 0, 512);
position = fs.Position;
char[] charData = new char[512];
//注意Read方法的第2个参数=0
Decoder dec = Encoding.ASCII.GetDecoder();
dec.GetChars(buffer, 0, buffer.Length, charData, 0);
var a=Convert.ToString(charData);
for (int i=0;i<charData.Length;i++)
{
countSplit = charData[i] == '{' ? countSplit + 1 : countSplit;
countSplit = charData[i] == '}' ? countSplit - 1 : countSplit;
//这里是判断要读取的数据的指针位置的一些条件
if (countSplit == 0 && charData[i] == '}')
{
//说明结束了,将指针移到这里
fs.Position = position - (charData.Length - 1 - i);
i = charData.Length+1;
break;
} else if ( i == charData.Length-1)
{
//说明这轮head还没结束
parseHeadByFileStream();
}
}
}
//这里判断条件是针对具体项目,懒得改了
public void parseData(int index, out byte[] data)
{
data = null;
if (fs.Position < MaxPosition)
{
//读指定长度的数组
data = binaryReader.ReadBytes(index);
}
else { fs.Close(); }
}