網(wǎng)站首頁 編程語言 正文
使用流讀取、寫入文件
使用流把文件讀取到字節(jié)數(shù)組:
//FileMode.Create, FileMode.Append
//FileAccess.Write, FileAccess.ReadWrite
//FileMode和FileAccess搭配使用,如果第二個(gè)參數(shù)FileMode.Appden寫追加,第三個(gè)參數(shù)FileAccess.Read只讀,會(huì)拋異常
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轉(zhuǎn)換:
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)
使用流把字節(jié)數(shù)組寫到文件:
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();
使用流對(duì)大文件進(jìn)行分批讀取和寫入:
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
基礎(chǔ)流
從流中讀取數(shù)據(jù):
CanRead()
Read(byte[] buffer, int offset, int count)
向流中寫入數(shù)據(jù):
CanWrite()
Write(byte[] buffer, int offset, int count)
WriteByte(Byte value)
移動(dòng)流指針:
CanSeek()
Seek(long offset, SeekOrigion)
Position流的指針位置
Close()
Dispose()
Flush()將緩存設(shè)備寫入存儲(chǔ)設(shè)備
CanTimeout()
ReadTimeout()
WriteTimeout()
Length
SetLength(long value)
裝飾器流
實(shí)現(xiàn)了Decorator模式,包含對(duì)Stream抽象基類的引用,同時(shí)繼承自Stream抽象基類。
- System.IO.Compression下的DeflateStream和GZipStream用于壓縮和解壓縮
- System.Security.Cryptography下的CryptoStream用于加密和解密
- System.Net.Security下的AuthenticatedStream用于安全性
- System.IO下的BufferedStream用戶緩存
包裝器類
不是流類型,而是協(xié)助開發(fā)者處理流包含的數(shù)據(jù),并且不需要將流讀取到Byte[]字節(jié)數(shù)組中。但流的包裝器類包含了對(duì)流的引用。
StreamReader
繼承自TextReader。
將流中的數(shù)據(jù)讀取為字符。
FileStream fs = new FileStream("a.txt", FileMode.Open, FileAcess.Read);
StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
//或者
//StreamReader reader = new StreamReader("a.txt"); //默認(rèn)采用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用于向流中以二進(jìn)制方式寫入基元類型,比如int, float, char, string等.BinaryReader用于從流中讀取基元類型。注意,這2個(gè)類并不是繼承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);
}
}
}
結(jié)果:
編碼方式:
定義了字節(jié)如何轉(zhuǎn)換成人類可讀的字符或者文本,可以看作是字節(jié)和字符的對(duì)應(yīng)關(guān)系表。在讀取文件采用的編碼方式要和創(chuàng)建文件采用的編碼方式保持一致。
幫助類
在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
相關(guān)推薦
- 2022-10-22 react實(shí)現(xiàn)消息顯示器_React
- 2022-07-08 關(guān)于Python與Golang語言的對(duì)比分析_其它綜合
- 2022-08-02 C#中的延時(shí)函數(shù)sleep_C#教程
- 2022-03-12 C++類和對(duì)象之多態(tài)詳解_C 語言
- 2023-07-04 Linux直接創(chuàng)建SSH無密碼連接
- 2022-04-07 C#接口INotifyPropertyChanged使用方法_C#教程
- 2022-09-01 C語言全面梳理結(jié)構(gòu)體知識(shí)點(diǎn)_C 語言
- 2023-12-06 Android百分比布局被棄用的問題
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支