文件读写(二)利用SteamReader和StreamWrite类处理字符串、FileSystemWatcher、BinaryReader/BinaryWriter
一、读写类:
TextReader/TextWriter:文本读写,抽象类
TextReader,其派生类:
- StreamReader:以一种特定的编码从字节流中读取字符。
- StringReader:从字符串读取。
TextWriter,其派生类:
- IndentedTextWriter:提供可根据 Tab 字符串标记缩进新行的文本编写器。
- StreamWriter:以一种特定的编码向流中写入字符。
- StringWriter:将信息写入字符串, 该信息存储在基础 StringBuilder 中。
- HttpWriter:提供通过内部 TextWriter 对象访问的 HttpResponse 对象。
- HtmlTextWriter:将标记字符和文本写入 ASP.NET 服务器控件输出流。 此类提供 ASP.NET 服务器控件在向客户端呈现标记时使用的格式化功能。
BinaryReader/BinaryWriter:二进制读写
- BinaryReader:用特定的编码将基元数据类型读作二进制值。
- BinaryWriter:以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。
XmlReader/XmlWriter :XML读写
见https://www.cnblogs.com/springsnow/p/9428695.html
二、StreamReader类读文件
构造函数:默认编码为UTF-8
public StreamReader (System.IO.Stream stream, System.Text.Encoding encoding );
public StreamReader (string path, System.Text.Encoding encoding)
实例:
StreamReader srAsciiFromFile = new StreamReader("C:\\Temp\\Test.txt", System.Text.Encoding.ASCII);
StreamReader srAsciiFromStream = new StreamReader( (System.IO.Stream)File.OpenRead("C:\\Temp\\Test.txt"),System.Text.Encoding.ASCII);
属性:
- BaseStream 返回基础流。
- CurrentEncoding 获取当前 StreamReader 对象正在使用的当前字符编码。
- EndOfStream 获取一个值,该值指示当前的流位置是否在流结尾。
方法:
- Peek() 返回下一个可用字符,但不使用它。
- Read() 读取输入流中的下一个字符并使该字符位置提升一个字符。
- Read(Char[], Int32, Int32) 从指定的索引位置开始将来自当前流的指定的最多字符读到缓冲区。
- ReadBlock(Char[], Int32, Int32) 从当前流中读取指定的最大字符数并从指定的索引位置开始将该数据写入缓冲区。
- ReadLine() 从当前流中读取一行字符并将数据作为字符串返回。
- ReadToEnd() 读取来自流的当前位置到结尾的所有字符。
- Close() 关闭 StreamReader 对象和基础流,并释放与读取器关联的所有系统资源。
- Dispose() 释放由 TextReader 对象使用的所有资源。
实例:
一、使用的实例StreamReader从文件读取文本 Read(),Peek()
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
二、调用其ReadAsync()方法以异步方式读取文件。
static async Task Main()
{
await ReadAndDisplayFilesAsync();
} static async Task ReadAndDisplayFilesAsync()
{
String filename = "C:\\s.xml";
Char[] buffer; using (var sr = new StreamReader(filename))
{
buffer = new Char[(int)sr.BaseStream.Length];
await sr.ReadAsync(buffer, 0, (int)sr.BaseStream.Length);
} Console.WriteLine(new String(buffer));
}
三、读取一行字符。ReadLine()
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
四、读取到一个操作中的文件的末尾。ReadToEnd()
using (StreamReader sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}
三、StreamWrite类写文件
构造函数
public StreamWriter (System.IO.Stream stream, System.Text.Encoding encoding);
public StreamWriter (string path, bool append, System.Text.Encoding encoding);
属性:
- BaseStream 获取同后备存储连接的基础流。
- Encoding 获取在其中写入输出的 Encoding。
- FormatProvider 获取控制格式设置的对象。
- NewLine 获取或设置由当前 TextWriter 使用的行结束符字符串。
方法:
- Write(**) 将 Boolean 值的文本表示形式写入文本字符串或流。
- WriteLine(**) 将行结束符的字符串写入文本字符串或流。
- Close() 关闭当前 StreamWriter 对象和基础流。
- Flush() 清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。
实例:
StreamWriter类允许直接将字符和字符串写入文件
//保留文件现有数据,以追加写入的方式打开d:\file.txt文件
using (StreamWriter sw = new StreamWriter(@"d:\file.txt", true))
{
//向文件写入新字符串,并关闭StreamWriter
sw.WriteLine("Another File Operation Method");
}
四、FileSystemWatcher
构造函数
给定要监视的指定目录和文件类型,初始化 FileSystemWatcher 类的新实例。
public FileSystemWatcher (string path, string filter);
属性
- EnableRaisingEvents 获取或设置一个值,该值指示是否启用此组件。
- Filter 获取或设置筛选字符串,用于确定在目录中监视哪些文件。
- IncludeSubdirectories 获取或设置一个值,该值指示是否监视指定路径中的子目录。
- NotifyFilter 获取或设置要监视的更改类型。
- Path 获取或设置要监视的目录的路径。
事件
- Created 当在指定 Path 中创建文件和目录时发生。
- Changed 当更改指定 Path 中的文件和目录时发生。
- Deleted 删除指定 Path 中的文件或目录时发生。
- Renamed 重命名指定 Path 中的文件或目录时发生。
实例:
下面的示例创建FileSystemWatcher监视在运行时指定的目录。 该组件设置为监视中的更改LastWrite和LastAccess时间、 创建、 删除、 或重命名的目录中的文本文件。 如果文件是更改、 创建,或删除,文件的路径将打印到控制台。 在一个文件重命名后,旧的和新路径将打印到控制台。
static void Main()
{
Run();
} [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private static void Run()
{
// Create a new FileSystemWatcher and set its properties.
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = "C:\\aa\\"; // Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files.
watcher.Filter = "*.txt"; // Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed; // Begin watching.
watcher.EnableRaisingEvents = true; // Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
} // Define the event handlers.
// Specify what is done when a file is changed, created, or deleted.
private static void OnChanged(object source, FileSystemEventArgs e) => Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
// Specify what is done when a file is renamed.
private static void OnRenamed(object source, RenamedEventArgs e) => Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
五、BinaryReader/BinaryWriter
读写流的基元数据类型。可以操作图像、压缩文件等二进制文件。不需要一个字节一个字节进行操作,可以是2个、4个、或8个字节这样操作。可以将一个字符或数字按指定数量的字节进行写入。
写入:
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
读取:
每次读取都回提升流中的当前位置相应数量的字节。下面的代码示例演示了如何存储和检索文件中的应用程序设置。
const string fileName = "AppSettings.dat";
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar; if (File.Exists(fileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
} Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
BinaryReader读取图片:
using (FileStream fs = new FileStream("1.jpg", FileMode.Open, FileAccess.Read))
{//将图片以文件流的形式进行保存
using (BinaryReader br = new BinaryReader(fs))
{
byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
br.Close();
}
}
文件读写(二)利用SteamReader和StreamWrite类处理字符串、FileSystemWatcher、BinaryReader/BinaryWriter的更多相关文章
- java byte【】数组与文件读写(增加新功能)
今天在测试直接写的文章: java byte[]数组与文件读写 时,想调用FileHelper类对字节数组以追加的方式写文件,结果无论怎样竟然数据录入不全,重新看了下文件的追加模式,提供了两种方式: ...
- node.js服务器核心http和文件读写
使用htpp给客服端的数据,把数据交给浏览器渲染.利用 http创建服务器,如客户端请求为:127.0.0.1:3000或127.0.0.1:3000/xxx.html时 ,判断www文件夹中,文件 ...
- 【03】Python 文件读写 JSON
1 打开文件 文件操作步骤: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件 3.关闭文件. 1.1 打开方法 f = open('xxx.txt') #需f.close( ...
- 文件读写(三)利用FileStream类操作字节数组byte[]、BinaryFormatter、内存流MemoryStream
一.Stream类概述 在.NET Framework中,文件和流是有区别的.文件是存储在磁盘上的数据集,它具有名称和相应的路径.当打开一个文件并对其进行读/写时,该文件就称为流(stream).但是 ...
- 【Hadoop】二、HDFS文件读写流程
(二)HDFS数据流 作为一个文件系统,文件的读和写是最基本的需求,这一部分我们来了解客户端是如何与HDFS进行交互的,也就是客户端与HDFS,以及构成HDFS的两类节点(namenode和dat ...
- 大数据【二】HDFS部署及文件读写(包含eclipse hadoop配置)
一 原理阐述 1' DFS 分布式文件系统(即DFS,Distributed File System),指文件系统管理的物理存储资源不一定直接连接在本地节点上,而是通过计算机网络与节点相连.该系统架构 ...
- C# 文件读写系列二
读取文件原则上非常简单,但它不是通过FileInfo和DirectoryInfo来完成的,关于FileInfo和DirectoryInfo请参考C# 文件操作系列一,在.Net Framework4. ...
- QT_8_Qt中的事件处理_定时器事件_定时器类_事件分发器_事件过滤器_绘图事件_高级绘图事件_绘图设备_QFile 文件读写_QFileInfo文件信息
Qt中的事件处理 1.1. 捕获QLabel中是鼠标事件 1.2. enterevent 鼠标进入 1.3. leaveevent 鼠标离开 1.4. 鼠标按下MyLabel::mousePressE ...
- [IO] C# INI文件读写类与源码下载 (转载)
/// <summary> /// 类说明:INI文件读写类. /// 编 码 人:苏飞 /// 联系方式:361983679 /// 更新网站:[url]http://www.sufei ...
随机推荐
- Python数据挖掘之随机森林
主要是使用随机森林将four列缺失的数据补齐. # fit到RandomForestRegressor之中,n_estimators代表随机森林中的决策树数量 #n_jobs这个参数告诉引擎有多少处理 ...
- Word 文档内超级链接跳转到书签
1. 前言 在Word文档内如何实现一些跳转的超链接呢?Word中,一些外部链接,我们通常叫作超链接,内部链接我们可以叫书签.如何在文档中如何使用书签,跳转到指定位置? 这里我在网上随便找了一份模拟试 ...
- ILSVRC比赛带来的算法
李飞飞和它的团队搜集了ImageNet一个超过15 million的图像数据集,大约有22,000类.这个文件集合对深度卷积网络极大地推进深度学习各领域的发展. ILSVRC是对ImageNet进行分 ...
- 创建 Python Virtualenv 虚拟隔离环境
video:创建 Python Virtualenv 虚拟隔离环境 python 虚拟环境 venv 简单用法 - littlemore - 博客园 创建 Python Virtualenv 虚拟隔离 ...
- RMAN备份脚本执行遇到RMAN-03002,06091问题处理
一 问题描述 客户说RMAN备份脚本执行有的时候报错,有的时候正常!!! 远程登陆客户环境,查询最后一次备份的日志报错信息,得到 RMAN-03002: failure of delete comma ...
- .NET Framework 4安装问题
1.安装时,系统提示:运行此安装程序之前,必须安装 32 位 Windows 映像处理组件(WIC). http://www.microsoft.com/downloads/zh-cn/details ...
- C# 字符串按设置的格试在前面或后面增加空格或其它字符
public string lengadd(string stringa, string stringb, int count, int mode) //以stringa的长度,未到count的长度则 ...
- 关键字:__thread & pthread_key_t
在说__thread之前,先来看看pthread_ket_t吧. 参考:http://blog.csdn.net/lmh12506/article/details/8452700 上面的博文说的比较通 ...
- 【转载】C#中PadLeft函数按特定字符补足字符串长度
在C#开发过程中字符串String类处理过程中,有时字符串长度不够时,需要在左侧指定特定的字符来补足字符串长度,此时可以使用String类下的PadLeft方法对字符串的左边进行按特定的字符和特定的长 ...
- 关于微信小程序分享/转发功能的实现方法
实现微信小程序分享,可以有两个入口: 1. 小程序右上角菜单自带的分享 这个入口是默认关闭的,需要在当前页面中调用showShareMenu方法,开启分享 onLoad: function () { ...