关于Stream系列实战
2024-09-15 14:00:29
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; namespace StreamTest
{
class Program
{
static void Main(string[] args)
{
byte[] buffer = null;
string testString = "Stream! Hello world";
char[] readCharArray = null;
byte[] readBuffer = null;
string readString = string.Empty;
//MemoryStream
using (MemoryStream stream = new MemoryStream())
{
Console.WriteLine("初始化字符串为:{0}", testString);
//如果该流可写
if (stream.CanWrite)
{
//尝试将testString写入流中
buffer = Encoding.Default.GetBytes(testString);
//我们从该数组的第一个位置开始写,长度为3,写完之后stream 中便有了数据
stream.Write(buffer, 0, 3);
Console.WriteLine("现在Stream.Positon在第{0}位置", stream.Position + 1);
//从刚才结束的位置往后移3位,到第7位 long newPositionInStream = stream.CanSeek ? stream.Seek(3, SeekOrigin.Current) : 0;
Console.WriteLine("重新定位后Stream.Position在第{0}位置", newPositionInStream + 1);
if (newPositionInStream <buffer.Length)
{
stream.Write(buffer, (int)newPositionInStream, buffer.Length - (int)newPositionInStream);
}
stream.Position = 0;
//设置一个空盒子来接收流中的数据,长度根据stream的长度来决定
readBuffer = new byte[stream.Length];
//设置stream 总的读取数量
//注意! 这时候流已经把数据读到了readBuffer中
int count = stream.CanRead ? stream.Read(readBuffer, 0, readBuffer.Length) : 0;
int charCount = Encoding.Default.GetCharCount(readBuffer, 0, count);
readCharArray = new char[charCount];
Encoding.Default.GetDecoder().GetChars(readBuffer, 0, count, readCharArray, 0);
for (int i = 0; i < readCharArray.Length;i++ )
{
readString += readCharArray[i];
}
Console.WriteLine("读取的字符串为:{0}", readString);
}
stream.Close();
}
Console.ReadLine();
}
}
}
最新文章
- tornado 第二种路由方法(装饰器)
- 收缩菜单 css变样
- mysql优化--触发器和auto_increment
- Volley框架的使用
- 九度OJ 1035:找出直系亲属(二叉树)
- LeetCode 59. Spiral Matrix II (螺旋矩阵之二)
- ml-agent:Win10下环境安装
- 阿里八八β阶段Scrum(2/5)
- Linux命令:linux软链接的创建、删除和更新---ln
- 【HDOJ1811】【并查集预处理+拓扑排序】
- JDBC是如何执行SQL脚本的
- Mysql的select in会自动过滤重复的数据
- Hbase和Hive的异同
- python之函数用法xrange()
- java-银行卡基本信息查询
- Android 实现透明效果的 Activity
- VC++为你的程序增加内存泄露检测
- Python一些特殊用法(map、reduce、filter、lambda、列表推导式等)
- java处理图片base64编码的相互转换
- windows平台下安装Beautiful Soup