c#文件读取与写入问题

rehtrht 2016-11-21 04:29:21
.txt文件中数据是小数,里面存了几千行数据,9个为一组数据,现在我只需要一组数据中前六个数据,我把每组的前六个数据,读取出来,再存入一个新建的2.txt中。现在我写了种方法,但是处理速度太慢了,1兆都要4分钟,求助
...全文
135 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
tcmakebest 2016-11-21
  • 打赏
  • 举报
回复
这样的写法不慢才怪, 用不着进行数字处理, 应直接按文字处理就好了. 读入一行数据, 找到第6个空格所在位置, 然后截取前面部分写入文件即可. 写文件不要写一行就打开关闭一次.
dalmeeme 2016-11-21
  • 打赏
  • 举报
回复
引用 4 楼 johnliuyuan 的回复:
设置个内存缓冲区,大概100M或者50M都行,每次读入相应大小的数据,进行处理,写入,重复直至完成
是这样的。
john_QQ:2335298917 2016-11-21
  • 打赏
  • 举报
回复
设置个内存缓冲区,大概100M或者50M都行,每次读入相应大小的数据,进行处理,写入,重复直至完成
rehtrht 2016-11-21
  • 打赏
  • 举报
回复
数据量可能到1G
dalmeeme 2016-11-21
  • 打赏
  • 举报
回复
不过几千条数据而已,建议一次性读取全部数据,然后在内存中处理,最后一次性写入新文件。
rehtrht 2016-11-21
  • 打赏
  • 举报
回复
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace writeDataTest { class Program { private int aa = 0; private void writeData(float [] Buf1) { if (Buf1 == null) return; using (StreamWriter writer = new StreamWriter("d:\\2.txt")) { for(int i = 0; i < 6; i++) { //for(int j = 0; j < ) //writer.Write(Buf1[i].ToString, i, Buf1[i]);//byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符. string a = Buf1[i].ToString(); //writer.WriteLine(a); writer.Write(Buf1[i].ToString()+" "); } writer.Write("\n"); } } private void saveData(string line, ref int iCount, ref int Buf1Number) { if(line == null) { return; } float[] Buf1 = new float[6]; var r = line.Split(' '); for (int i = 0; i < r.Length; i++) { if (iCount < 6) { Buf1[Buf1Number] = float.Parse(r[Buf1Number]);//存入数据 Buf1Number++; } iCount++; if (Buf1Number == 6)//存入飞机坐标、姿态后写入到文件中 { writeData(Buf1); Buf1Number = 0; } if (iCount == 9) { iCount = 0; } } } private void Gettext()//从文本中读取数据 { int Buf1Number = 0; int iCount = 0; using (StreamReader reader = new StreamReader("d:/3.txt")) { //reader.BaseStream.Seek string line = "1"; while (line != null) { line = reader.ReadLine();//一行一行读取文本中的数据 saveData(line,ref iCount,ref Buf1Number); aa++; } } } static void Main(string[] args) { Program a = new Program(); a.Gettext(); } } }

110,502

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧