Chinaunix首页 | 论坛 | 博客
  • 博客访问: 987441
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C#/.net

2013-03-18 11:03:38

前几天遇到一个面试题。大意是从给一个文件A读取数据,然后对读取到数据做某种处理,然后输出到文件B.
写的时候想当然就使用StreamReader.ReadLine这种。实际interviewer提醒要考虑文件很大的情况。可惜我也从未处理过大文件的情况,直接说不会。现在把问题记录如下。

对于StreamReader来说,本身大文件应该是不会引起new的时候问题,关键问题在于ReadLine时,如果是超长的一行,可能会引起溢出问题。

MSDN也标注了这个Exception:
OutOfMemory Exception: There is insufficient memory to allocate a buffer for the returned string. 
 

所以读取的时候,如果无法确定大小,或者已知是大文件,应该使用Read(Char[], Int32, Int32)方法替代
Read(Char[], Int32, Int32): Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index. (Overrides TextReader.Read(Char[], Int32, Int32).)

即每次读取指定大小的内容。
第一个参数为buffer,用来存储读取的内容。
第二个参数为index,从stream的该出进行读取。
第三个参数为size,读取的char的数量。

对于java,使用FileInputStream也有类似的 方法
int         read(byte[] b)
int         read(byte[] b, int off, int len)

点击(此处)折叠或打开

  1. using (StreamReader sr = new StreamReader(path))
  2.             {
  3.                 //This is an arbitrary size for this example.
  4.                 char[] c = null;

  5.                 while (sr.Peek() >= 0)
  6.                 {
  7.                     c = new char[5];
  8.                     sr.Read(c, 0, c.Length);
  9.                     //The output will look odd, because
  10.                     //only five characters are read at a time.
  11.                     Console.WriteLine(c);
  12.                 }
  13.             }


阅读(1727) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~