StreamReader类的方法不是静态方法,所以要使用该类读取文件首先要实例化该类,在实例化时,要提供读取文件的路径。
我在这把文件放在了bin目录下,所以路径不用写全,代码很简单,基本就是切割再切割
为了省事,我把文本写成了这样,冒号前面是名字什么的,后面是具体数值
StreamReader SR = File.OpenText(@"FishModel.txt");
string Line = SR.ReadToEnd();// 所有鱼的数据,存在一个字符串
string[] everyLine = null;
everyLine = Line.Split('|');// 单条鱼的所有数据存在数组,逗号隔开
string[] everyData = null;
string a;
Console.WriteLine("加载鱼的数据...");
foreach (string item in everyLine)
{
everyData = item.Split(':');// 切割出单个数据
a = everyData[1];
string[] str = a.Split(',');
string name = str[0];
int id = int.Parse(str[1]);
int life = int.Parse(str[2]);
int speed = int.Parse(str[3]);
int killBouns = int.Parse(str[4]);
int count_Max = int.Parse(str[5]);
int KillBounsDiamond = int.Parse(str[6]);
FishModel fish = new FishModel(id, life, speed, killBouns, count_Max, KillBounsDiamond)
this.fishList.Add(fish);
Console.WriteLine(
"[fish] name: " + name
+ "\tid: " + id
+ "\tlife: " + life
+ "\tspeed: " + speed
+ "\tkillBonus: " +killBouns
+ "\tcount_max: " + count_Max
+ "\tkillBonusDiamond: " + KillBounsDiamond);
}
SR.Close();
用完StreamReader之后,要记得关闭 SR.Close();
string Line = SR.ReadToEnd(); 这里的ReadToEnd是一次全部读完内容,还可以一次读一个字节,读一行等等,如下
// 读一行
string nextLine = SR.ReadLine();
// 读一个字符
int nextChar = SR.Read();
// 读100个字符
int n = 100;
char[] charArray = new char[n];
int nCharsRead = SR.Read(charArray, 0, n);
// 全部读完
string restOfStream = SR.ReadToEnd();
还可以用File.ReadAllLines,该方法一次性读取文本内容的所有行,返回一个字符串数组,数组元素是每一行的内容
string[] strs1 = File.ReadAllLines(@"c:\temp\a.txt");