1.流的含义

流是一系列具有方向性的字节序列,比如水管中的水流,只不过现在管道中装的不是水,而是字节序列。当流是用于向外部目标比如磁盘输出数据时称为输出流,当流是用于把数据从外部目标读入程序称为输入流。

2.文件读写

写入

            string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
string strData = "Hello to you";
byte[] byteData = Encoding.UTF8.GetBytes(strData);
fs.Write(byteData, , byteData.Length);

读取

            string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read); byte[] buffer = new byte[];
int count =;
MemoryStream ms = new MemoryStream();
while ((count = fs.Read(buffer, , buffer.Length)) > )
{
ms.Write(buffer, , buffer.Length);
}
string strData= Encoding.UTF8.GetString(ms.ToArray());

注:File.Open方法不传FileAccess参数时,默认FileAcross.ReadWrite

3.StreamReader/StreamWriter流读写器

FileStream读写文件是直接对字节流进行操作的并不能对字符直接进行输入输出,使用StreamReader/StreamWriter可以方便的对字符/字符串进行操作。通常情况下都会把FileStream等其他流包装在StreamReader/StreamWriter中,因为这些类更容易对流进行处理。

3.1读写文本文件

写入

            string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read); StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Hello to you");
sw.Write("It's now {0}", DateTime.Now.ToString());//格式化字符串 sw.Close();
fs.Close();

读取

            string fileName = Server.MapPath("log.txt");
FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string lines="";
string line = sr.ReadLine();
lines += line;
while (line!=null)
{
line = sr.ReadLine();
lines += line;
}
txtContent.Text = lines;
sr.Close();
fs.Close();

注:StreamReader/StreamWriter本身不能对文件进行FileMode,FileAccess等权限控制,如果要控制需要在包装的流中进行

StreamReader读取二进制文件

            string fileName = Server.MapPath("img\\中文Begrüßung.png");
StreamReader sr = new StreamReader(File.OpenRead(fileName));
byte[] buffer = new byte[];
int count;
MemoryStream ms = new MemoryStream();
while ((count = sr.BaseStream.Read(buffer, , buffer.Length)) > )
{
ms.Write(buffer, , count);
} string fileName2 = Server.MapPath("img\\中文2.png");
FileStream fs = File.Open(fileName2, FileMode.OpenOrCreate);
ms.WriteTo(fs);
fs.Close();
sr.Close();

StreamReader读取二进制文件需要用到BaseStream,不能像读写文本文件那样,否则保存的文件不能用。

4.对象序列化为二进制数据

程序一般保存的数据都不是像一般的文本文件那样直接写入文本逐行保存的,而是以二进制数据的形式保存的,使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatter可以把对象序列化为二进制数据,或者把二进制数据序列化为对象。

[Serializable]
public class Product
{
public long Id;
public string Name;
public double Price; [NonSerialized]
string Notes; public Product(long id, string name, double price, string notes)
{
this.Id = id;
this.Name = name;
this.Price = price;
this.Notes = notes;
} public override string ToString()
{
return string.Format("{0},{1},${2:F2},{3}",Id,Name ,Price ,Notes);
}
}

序列化/反序列化

            List<Product> products = new List<Product>();
products.Add(new Product(, "poky", 10.2, "pokys"));
products.Add(new Product(, "kuti", 2.34, "第四方")); //序列化对象保存到文件
string fileName = Server.MapPath("ser.txt");
FileStream fs = File.Open(fileName, FileMode.OpenOrCreate);
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(fs, products);
fs.Close(); //反序列化
FileStream ls = File.Open(fileName, FileMode.OpenOrCreate);
List<Product> ps = serializer.Deserialize(ls) as List<Product>;
ls.Close();

注:这里是序列化为二进制数据,所以和序列化为Json/xml是不一样的。

5.压缩/解压数据

如果要保存的数据比较大,还可以对数据进行压缩再保存,但是这里的压缩是单纯压缩数据,不是压缩文件,所以和常用的压缩解压工具是不一样的。

    public class CompressDAL
{
/// <summary>
/// 创建一个压缩文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="data"></param>
public static void SaveCompressFile(string fileName, string data)
{
FileStream fs = File.Open(fileName, FileMode.Create,FileAccess.Write);
GZipStream gs = new GZipStream(fs, CompressionMode.Compress);
StreamWriter sw = new StreamWriter(gs);//向压缩流写入数据
sw.Write(data);
sw.Close();
} public static string LoadeCompressFile(string fileName)
{
FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);
GZipStream gs = new GZipStream(fs, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gs);
string lines = sr.ReadToEnd();
return lines;
} }
 string data = "叫爸爸\n叫爸爸\n";

            string fileName = Server.MapPath("gzFile.txt");
CompressDAL.SaveCompressFile(fileName, data);
string content = CompressDAL.LoadeCompressFile(fileName);

最新文章

  1. Java 线程池的介绍以及工作原理
  2. 补一篇关于Jackson和Gson的文章
  3. Floyd算法解决最短路径问题
  4. ASP.NET MVC(三) TypeScript
  5. [Openstack]使用devstack自己主动化安装
  6. 在vue2.0中使用sass
  7. 跟我一起读postgresql源码(十六)——Executor(查询执行模块之——control节点(下))
  8. luogu P2194 HXY烧情侣
  9. Java SE API —— 【Math 】之【BigInteger】类
  10. python模块的使用
  11. Codeforces 101623E English Restaurant - 动态规划
  12. BashOnWindow安装mysql
  13. echarts 导出图片,并将图片导出pdf格式
  14. 通过msyql proxy链接mysql中文乱码及session问题
  15. python中除法的注意事项
  16. Linux 下载最新kubectl版本的命令:
  17. selenium常用获取元素点
  18. 使用Redis+java(模仿数据库)实现对象存取和读取
  19. ASP.NET学习路线图(转)
  20. Android Studio 常用技巧

热门文章

  1. 关于mathtype6.9在office2010中出现The MathType can not be found的问题
  2. web框架之Django
  3. MySQL(四)InnoDB中一棵B+树能存多少行数据
  4. pytorch1.0实现GAN
  5. [.Net Core] - 当 .Net Core 版本由 1.x 升级至 2.x 后,Cookie 使用方式变更
  6. Java:session中的invalidate()的作用是什么呢?求解
  7. Python21之内嵌函数和闭包
  8. Oracle和SQL Server 用当前日期减去 &#39;0001-01-01&#39; 得出的天数不一致,相差2天,谁知道原因?
  9. Springboot对JPA的支持及使用
  10. ES6语法基本使用