文件读写(二)利用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 ...
随机推荐
- 第07组 Alpha冲刺(2/4)
队名:秃头小队 组长博客 作业博客 组长徐俊杰 过去两天完成的任务:完成人员分配,初步学习Android开发 Github签入记录 接下来的计划:继续完成Android开发的学习,带领团队进行前后端开 ...
- PHP 与操作判断奇偶
/** * 判断奇偶数 * @param $n * @return int */ function isOdd($n){ // $a & $b And(按位与) 将把 $a 和 $b 中都为 ...
- 怎样ubuntu下命令行终端显示短路径
参考:http://blog.sina.com.cn/s/blog_b71132f001016cmm.html ubuntu的终端命令行默认是长路径,即把路径深度全部显示出来,操作起来不是很方便,下面 ...
- Python re模块学习
这是re模块与正则的结合 re模块提供的函数 1.match 尝试在字符串的开头应用该模式,返回匹配对象,如果没有找到匹配,则为None. import re str1 = "Why ar ...
- Python进阶:metaclass谈
metaclass 的超越变形特性有什么用? 来看yaml的实例: import yaml class Monster(yaml.YAMLObject): yaml_tag = u'!Monster' ...
- PAT(B) 1049 数列的片段和(C)规律
题目链接:1049 数列的片段和 (20 point(s)) 题目描述 给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段.例如,给定数列 { 0.1, 0.2, 0.3, 0.4 },我 ...
- LINUX驱动笔记 目录
笔记参考了宋宝华老师的<Linux设备驱动开发详解:基于最新的Linux 4.0内核>以及韦东山老师的嵌入式驱动教程 笔记开发环境: 单板:第一章到第八章使用TINY4412-1611:第 ...
- C#使用管理员权限打开cmd执行命令行
最近遇到个棘手的问题,服务器远程连不上,但是ftp可以,可能远程连接的服务挂了或者防火墙入站规则有点问题,想要重启,得找机房工作人员,还是挺麻烦的 想了想可以上传个执行cmd命令的东西,然后远程访问触 ...
- shell 学习笔记7-shell-函数
一.函数 1.什么是shell函数 把相同程序段定义成函数,可以减少整个程序的代码量,提升开发效率 增加程序的可读性,易读性,提升管理效率 可以失效程序功能模块化,使程序具备可移植性 其实linux系 ...
- Linux入职基础-1.2_U盘安装RedHat5具体步骤
从U盘安装RedHat5具体步骤 从U盘安装RedHat Linux的具体步骤: 准备工作: RHEL_5.6_i386_DVD.ISO文件 具体步骤: 1.解压并用ultraiso软件打开rhel- ...