C#中流的使用和分类
作者:Darren?Ji 发布时间:2022-10-04 22:17:41
使用流读取、写入文件
使用流把文件读取到字节数组:
//FileMode.Create, FileMode.Append
//FileAccess.Write, FileAccess.ReadWrite
//FileMode和FileAccess搭配使用,如果第二个参数FileMode.Appden写追加,第三个参数FileAccess.Read只读,会抛异常
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read)
byte[] buffer = new byte[source.Length];
int bytesRead = source.Read(buffer, i, (int)source.Length);
Int32类型的最大值,以及Byte, KB, MB, GB转换:
Int32.MaxValue = 2147483647 Byte
2147483647/1024 = 2097152 KB(1 KB = 1024 Byte)
2097152/1024 = 2048 MB(1 M = 1024 KB)
2048/1024 = 2 G(1G = 1024M)
使用流把字节数组写到文件:
Stream target = new FileStream(@"2.jpg", FileMode.Create, FileAccess.Write);
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read)
byte[] buffer = new byte[source.Length];
int bytesRead = source.Read(buffer, i, (int)source.Length);
target.Write(buffer, 0, buffer.Length);
source.Dispose();
target.Dispose();
使用流对大文件进行分批读取和写入:
int BufferSize = 10240; // 10KB
Stream source = new FileStream(@"D:\a.mp3", FileMode.Open, FileAccess.Read);
Stream target = new FileStream(@"D:\b.mp3", FileMode.Create, FileAccess.Write);
byte[] buffer = new byte[BufferSize];
int byteRead;
do{
byteRead = source.Read(buffer, 0, BufferSize);
target.Write(buffer, 0, bytesRead);
} while(byteRead > 0);
target.Dispose();
source.Dispose();
流的分类
在Stream抽象类下包含:
→FileStream→IsolatedStoreageFileStream
→MemoryStream
→NetworkStream
基础流
从流中读取数据:
CanRead()
Read(byte[] buffer, int offset, int count)
向流中写入数据:
CanWrite()
Write(byte[] buffer, int offset, int count)
WriteByte(Byte value)
移动流指针:
CanSeek()
Seek(long offset, SeekOrigion)
Position流的指针位置
Close()
Dispose()
Flush()将缓存设备写入存储设备
CanTimeout()
ReadTimeout()
WriteTimeout()
Length
SetLength(long value)
装饰器流
实现了Decorator模式,包含对Stream抽象基类的引用,同时继承自Stream抽象基类。
System.IO.Compression下的DeflateStream和GZipStream用于压缩和解压缩
System.Security.Cryptography下的CryptoStream用于加密和解密
System.Net.Security下的AuthenticatedStream用于安全性
System.IO下的BufferedStream用户缓存
包装器类
不是流类型,而是协助开发者处理流包含的数据,并且不需要将流读取到Byte[]字节数组中。但流的包装器类包含了对流的引用。
StreamReader
继承自TextReader。
将流中的数据读取为字符。
FileStream fs = new FileStream("a.txt", FileMode.Open, FileAcess.Read);
StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
//或者
//StreamReader reader = new StreamReader("a.txt"); //默认采用UTF-8编码方式
StreamWriter
继承自TextWriter。
将字符写入到流中。
string text =
@"aa
bb
cc";
StringReader reader = new StringReader(text);
int c = reader.Read();
Console.Write((char)c);
char[] buffer = new char[8];
reader.Read(buffer, 0, buffer.Length);
Console.Write(String.Join("",buffer));
string line = reader.ReadLine();
Console.WriteLine(line);
string rest = reader.ReadToEnd();
Console.Write();
reader.Dispose();
StringReader和StringWriter
也继承自TextReader和TextWriter,但是用来处理字符串。
BinaryWriter和BinaryReader
BinaryWriter用于向流中以二进制方式写入基元类型,比如int, float, char, string等.BinaryReader用于从流中读取基元类型。注意,这2个类并不是继承TextReader和TextWriter。
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
Product p = new Product("product.bin")
{
Id = 1,
Name = "GOOD",
Price = 500F
};
p.Save();
Product newP = new Product("product.bin");
newP.Load();
Console.WriteLine(newP);
Console.ReadKey();
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
private string filePath;
public Product(string filePath)
{
this.filePath = filePath;
}
public void Save()
{
FileStream fs = new FileStream(this.filePath, FileMode.Create,FileAccess.Write);
BinaryWriter writer = new BinaryWriter(fs);
writer.Write(this.Id);
writer.Write(this.Name);
writer.Write(this.Price);
writer.Dispose();
}
public void Load()
{
FileStream fs = new FileStream(this.filePath, FileMode.Open,FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
this.Id = reader.ReadInt32();
this.Name = reader.ReadString();
this.Price = reader.ReadDouble();
reader.Dispose();
}
public override string ToString()
{
return String.Format("Id:{0},Name:{1},Price:{2}", this.Id, this.Name, this.Price);
}
}
}
结果:
编码方式:
定义了字节如何转换成人类可读的字符或者文本,可以看作是字节和字符的对应关系表。在读取文件采用的编码方式要和创建文件采用的编码方式保持一致。
帮助类
在System.IO命名空间下。
File
FileStream fs = File.Create("a.txt");
Open(string path, FileMode mode)
OpenRead()
OpenWrite()
ReadAllText()
ReadAllByte()
WriteBllBytes()
WriteAllLines()
Copy(string sourceFileName, string destFileName)
FileInfo
Path
Directory
DirectoryInfo
来源:https://www.cnblogs.com/darrenji/p/3657740.html


猜你喜欢
- 用Java编写简单的五子棋,供大家参考,具体内容如下前言这两天在空闲时间做了个五子棋项目,分享给大家看一下,界面是这样的:界面很丑我知道,本
- 本文通过JavaMailSender实现邮箱注册验证中遇到的问题开始着手,给大家详细分析了其原理以及问题的解决办法。使用邮箱注册验证,我们需
- 前言本文主要介绍了关于JDK源码分析之String、StringBuilder和StringBuffer的相关内容,分享出来供大家参考学习,
- 一、准备工作mybatis-plus作为mybatis的增强工具,它的出现极大的简化了开发中的数据库操作,但是长久以来,它的联表查询能力一直
- 前言《布谷鸟闯关-简单版》是一个基于java的布谷鸟闯关游戏,摁上键控制鸟的位置穿过管道间的缝隙,需要做碰撞检测,监听键盘事件,背景图片的切
- 用一个7 x 7的矩形表示迷宫,0和1分别表示的是通路和障碍。通过设计编写程序找到蓝色小球达到蓝色旗子的路线思路:构建一个迷宫(用二维数组)
- 下面的每一步应该都必不可少:1、启动类继承这个类,并且重新configure这个方法,return builder.sources(Code
- 前言老了,老了,那天有位小同事问我Android跳转三方应用时有什么要注意的?是否可以直接跳?如何传递参数过去? 嗯… 我竟然说需要root
- 这篇文章主要介绍了springmvc处理模型数据ModelAndView过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一
- 结构是使用 struct 关键字定义的,例如:public struct PostalAddress{ // Fields, propert
- 目录前言HuTool 中的一些常用工具类日期相关 API随机工具图片工具彩色转换成黑白添加文字水印加密解密工具布隆过滤器邮件工具HTML 工
- Write()和WriteLine()都是System.Console提供的方法,两着主要用来将输出流由指定的输出装置(默认为屏幕)显示出来
- 方法一:利用两个指针p,q,首先将q往链表尾部移动n位,然后再将p、q一起往后移,那么当q达到链表尾部时,p即指向链表的倒数第n个节点。no
- 若干年前在使用SpringMVC的时候,发现springMVC可以把HttpSession,HttpRequest组件化注入:@Autowi
- 面对android studio Run 一次项目要等好几分钟的痛点,不得不研究一下android studio 的单元测试。其实我的目的很
- Object(四大方法):文章干货满满,耐性看完~~何为Object?首先先来看看官方对Object的介绍:在这里附上Java官方的查阅工具
- 我在5月份的时候就申请了洞态IAST企业版内测,算是比较早的一批用户了。聊聊几个我比较在意的问题,比如API接口覆盖率、第三方开源组件检测以
- 一、写在前面数据结构中的队列应该是比较熟悉的了,就是先进先出,因为有序故得名队列,就如同排队嘛,在对尾插入新的节点,在对首删除节点.jdk集
- 这一篇文章介绍SpringBoot应用修改默认打jar形式部署为打war包形式,部署到外部Tomcat。SpringBoot应用默认打包成为
- 一.什么是多渠道打包在不同的应用市场可能有不同的统计需求,需要为每个应用市场发布一个安装包,这里就引出了Android的多渠道打包。在安装包