您的位置:首页 > 职场人生

黑马程序员 C#学习笔记⑧ StreamReader和StreamWriter

2014-03-24 11:55 507 查看
----------------------
ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

StreamWriter对象

操作字节数组比较麻烦, 对于FileStream对象, 通常会创建一个StreamWrite或者StreamReader, 并使用它们的方法来处理文件. 如果不需要改变文件指针到任意位置,这些类就很容易操作文件.

FileStreamaFIle = new FileStream("Log.txt", FileMode.CreateNew);

StreamWritersw = new StreamWriter(aFIle);

也可以直接从文件中创建StreamWriter对象:
StreamWritersw = new StreamWriter("Log.txt", true);

构造函数

public StreamWriter(

stringpath,

boolappend

)

参数

path

类型:System.String

要写入的完整文件路径。

append

类型:System.Boolean

若要追加数据到该文件中,则为true;若要覆盖该文件,则为 false。 如果指定的文件不存在,该参数无效,且构造函数将创建一个新文件。

StreamWriter对象不会提供类似于FileStream中的类似选项: 没有想FileStream类中那样指定FileMode和FileAccess的选项. 总是保有读写权限, 为了使用FileStream的高级参数, 先在FileStream对象中定义这些参数, 然后通过FileStream对象创建StreanWriter对象.

使用StreamWriter

using System;

usingSystem.Collections.Generic;

using System.Linq;

using System.Text;

usingSystem.Threading.Tasks;

using System.IO;

namespace 使用StreamWriter

{

class Program

{

static void Main(string[] args)

{

try

{

FileStream aFile = newFileStream("Log.txt", FileMode.OpenOrCreate);

StreamWriter sw = newStreamWriter(aFile);

bool truth = true;

//向文件中写入数据

sw.WriteLine("Hello toyou.");

sw.WriteLine("It is now{0} and things are looking good.",

DateTime.Now.ToLongDateString());

sw.Write("More thanthat,");

sw.Write(" it's {0} thatC# is fun.", truth);

sw.Close();

}

catch (IOException e)

{

Console.WriteLine("An IOexception has been throw");

Console.WriteLine(e.ToString());

Console.ReadLine();

return;

}

}

}

}

该程序生成一个Log.txt文件, 由于使用的是相对路径, 因此和应用程序处于同一个文件夹下. 可以看出StreamWriter对于文件的处理十分方便.

StreamReader

基本和StreamWriter类似

using System;

usingSystem.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

usingSystem.Threading.Tasks;

namespace 使用StreamReader

{

class Program

{

static void Main(string[] args)

{

string line;

try

{

FileStream aFile = newFileStream(@"E:\Visual Studio 2012Projects\Projects\StreamWriter\StreamWriter\bin\Debug\Log.txt",FileMode.Open);

StreamReader sr = newStreamReader(aFile);

line = sr.ReadLine();

//Read data in line by line

while (line != null)

{

Console.WriteLine(line);

line = sr.ReadLine();

}

sr.Close();

}

catch (IOException e)

{

Console.WriteLine("An IOexception has been thrown");

Console.WriteLine(e.ToString());

return;

}

Console.ReadKey();

}

}

}

该程序使用绝对路径读取刚刚创建的Log.txt, 并输出其中的内容.

读取数据的其他方法

StreamReader类中的Read()方法, 此方法将流的下一个字节作为正整数返回, 如果到达了流的结尾处, 则返回-1. 使用Convert实用类可以把这个值转换为字符.

StreamReadersr = new StreamReader("Log.txt");

intcharCode;

charCode =sr.Read();

while(charCode!= -1)

{

Console.Write(Convert.ToChar(charCode));

charCode = sr.Read();

}

sr.Close();

处理大型文件的另一种方式是使用File类中的ReadLines

File.ReadLines(); 返回一个Ienumerable<string>集合, 可以直接用于遍历,, 操作简便.

用分隔符分隔的文件

CSV文件

一般使用逗号分隔存储数据

标准处理程序

using System;

usingSystem.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

usingSystem.Threading.Tasks;

namespaceCommaValues

{

class Program

{

static void Main(string[] args)

{

List<string> columns;

List<Dictionary<string,string>> myData = GetData(out columns);

foreach (string column in columns)

{

Console.Write("{0,-20}", column);

}

Console.WriteLine();

foreach (Dictionary<string,string> row in myData)

{

foreach (string column incolumns)

{

Console.Write("{0,-20}", row[column]);

}

Console.WriteLine();

}

Console.ReadKey();

}

static List<Dictionary<string,string>> GetData(

out List<string> columns)

{

string line;

string[] stringArray;

char[] charArray = new char[] {','};

List<Dictionary<string,string>> data = new List<Dictionary<string, string>>();

columns = newList<string>(); //out传参需要在函数内部初始化

try

{

FileStream aFile = newFileStream("SomeData.txt", FileMode.Open);

StreamReader sr = newStreamReader(aFile);

//读取第一行, 第一行中都是列名, 使用split()方法分隔字符串

line = sr.ReadLine();

stringArray =line.Split(charArray);

for (int x = 0; x <stringArray.GetUpperBound(0); x++)

{

columns.Add(stringArray[x]);

}

line = sr.ReadLine();

while (line != null)

{

//将line中的内容分割成字符串数组

stringArray =line.Split(charArray);

Dictionary<string,string> dataRow = new Dictionary<string, string>();

for (int x = 0; x <stringArray.GetUpperBound(0); x++)

{

dataRow.Add(columns[x],stringArray[x]);

}

data.Add(dataRow);

line = sr.ReadLine();

}

sr.Close();

return data;

}

catch (IOException e)

{

Console.WriteLine("An IOexception has been thrown!");

Console.WriteLine(e.ToString());

Console.ReadKey();

return data;

}

}

}

}

知识点:

GetData方法中使用了out传参, out传参和ref传参的主要区别就是out传参的参数要在函数内部初始化, 而ref参数需要在外部初始化, 也就是赋值. 都需要在外部先声明变量.

split()方法中的参数是char[]类型

Array类的GetUpperBound(rank)方法 获得当前数组rank维度中元素索引的上限, 也就是元素个数-1, 应用在多维数组中.

和Length的区别就是Length是所有维度中元素个数.

在GetData方法中, 定义了一个Dictionaty<string, string>集合, 用于保存读取的数据. 定义一个Dictionary<string,string>对象保存每行的数据, 类似于DataTable和DataRow的关系. 使用列名作为键, 数值保存在值中.

还使用了out传参, 传出columns, 这个变量中保存的是列名(也就是文件的第一行). 列名作为数据的键值一起存储在Dictionary<string,string>中, 用于保存和输出. 在外部就可以使用row[column]调用.

Console.Write("{0, -20}",row[column]); 格式项语

{索引[,对齐][:格式字符串]}

索引组件

强制“索引”组件(也叫参数说明符)是一个从0 开始的数字,可标识对象列表中对应的项。 也就是说,参数说明符为 0 的格式项列表中的第一个对象,参数说明符为 1 的格式项列表中的第二个对象,依次类推。

通过指定相同的参数说明符,多个格式项可以引用对象列表中的同一个元素。例如,通过指定类似于“{0:X} {0:E} {0:N}”的复合格式字符串,可以将同一个数值设置为十六进制、科学记数法和数字格式。

每个格式项都可以引用列表中的任一对象。例如,如果有三个对象,则可以通过指定类似于“{1} {0} {2}”的复合格式字符串来设置第二、第一和第三个对象的格式。 格式项未引用的对象会被忽略。如果参数说明符指定了超出对象列表范围的项,将导致运行时异常。

对齐组件

可选的“对齐”组件是一个带符号的整数,指示首选的设置了格式的字段宽度。如果“对齐”值小于设置了格式的字符串的长度,“对齐”会被忽略,并且使用设置了格式的字符串的长度作为字段宽度。如果“对齐”为正数,字段中设置了格式的数据为右对齐;如果“对齐”为负数,字段中的设置了格式的数据为左对齐。 如果需要填充,则使用空白。如果指定“对齐”,就需要使用逗号。

格式字符串组件

可选的“格式字符串”组件是适合正在设置格式的对象类型的格式字符串。如果相应的对象是数值,则指定标准或自定义的数字格式字符串;如果相应的对象是 DateTime 对象,则指定标准或自定义的日期和时间格式字符串;或者,如果相应的对象是枚举值,则指定 枚举字符格式。如果不指定“格式字符串”,则对数字、日期和时间或者枚举类型使用常规(“G”)格式说明符。 如果指定“格式说明符”,需要使用冒号。

----------------------
ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------详细请查看:www.itheima.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐