IO&&Serize 利用线程Thread.Sleep实现"自动输出"
查看链接 https://github.com/jungle8884/C-.Net/tree/MyClassLibrary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Jungle8884
{
/// <summary>
/// 对应于SerializeHelper,必须添加可序列化特性
/// </summary>
[Serializable]
public class Person
{
[NonSerialized]
public int Id = ; public string Name { get; set; } public string Gender { get; set; } } [Serializable]
public class Programmer : Person
{
private string Language { get; set; } public string Description { get; set; } } /// <summary>
/// 数据工厂
/// </summary>
public class DataFactory
{
/// <summary>
/// 初始化数据---用于测试
/// </summary>
/// <returns></returns>
public static List<Programmer> BuildProgrammerList()
{
#region data-prepare
List<Programmer> list = new List<Programmer>();
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "SoWhat",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "day",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "领悟",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "Sam",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "AlphaGo",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "折腾",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "Me860",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "打兔子的猎人",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "Nine",
Gender = "女"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "望",
Gender = "女"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "微笑刺客",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "waltz",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "爱在昨天",
Gender = "男"
});
list.Add(new Programmer()
{
Id = ,
Description = "高级班学员",
Name = "waltz",
Gender = "男"
});
#endregion return list;
}
}
}
数据准备
IO: 97和69两行可以模拟控制台自动输出---模拟黑客。。。
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;
using System.Threading; namespace Jungle
{
public class MyIO
{
//日志文件名
private static string sLogFileName = Path.Combine(MyConstants.LogPathAbsolute, "Log.txt");
/// <summary>
/// 写日志
/// </summary>
/// <param name="sWriteIn"></param>
public static void WriteLogsWriteLine(string sWriteIn)
{
if (!File.Exists(sLogFileName))
{
//1 先创建文件夹
Directory.CreateDirectory(MyConstants.LogPathAbsolute);
//2 再创建文件
using (FileStream fileStream = File.Create(sLogFileName))//打开文件流 (创建文件并写入)
{
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(sWriteIn);
sw.Flush();
#region 其他方法---字节流
//byte[] bytes = Encoding.Default.GetBytes(sWriteIn);
//fileStream.Write(bytes, 0, bytes.Length);
//fileStream.Flush();
#endregion
}
}
}
/// <summary>
/// 写日志---追加
/// </summary>
public static void WriteLogsAppendText(string sWriteIn)
{
using (StreamWriter sw = File.AppendText(sLogFileName))
{
sw.WriteLine(sWriteIn);
sw.Flush();
} } /// <summary>
/// 读取日志输出到控制台
/// 适合小数据文件
/// </summary>
public static void ReadLogsToConsole()
{
foreach (string sResult in File.ReadAllLines(sLogFileName))
{
#region 其他方法---仅供参考
//string sResult = File.ReadAllText(sLogFileName);//一次性读取所有的文本 //Byte[] byteContent = File.ReadAllBytes(sLogFileName);//字节流的方式读取
//string sResultByte = Encoding.UTF8.GetString(byteContent);//字节流解码为字符串
#endregion
char[] cResult = sResult.ToCharArray();
foreach (char c in cResult)
{
Console.Write(c);
Thread.Sleep(200);
}
Console.WriteLine();
}
} /// <summary>
/// 读取大文件使用(当然小文件一样适用)
/// 采用策略:分批读取
/// </summary>
public static void ReadLargeFileToConsole()
{
using (FileStream stream = File.OpenRead(sLogFileName))
{
int iLength = ;//指定每次读取长度
int iResult = ; do
{
byte[] bytes = new byte[iLength];
iResult = stream.Read(bytes,,iLength);//返回读取的字节数
Console.Write((Encoding.UTF8.GetString(bytes, , iResult)));//直接输出一句
#region 按字节输出
//for (int i = 0; i < iResult; i++)
//{
// Console.Write((bytes[i].ToString()));
//}
#endregion
Thread.Sleep(300);
}
while (iLength == iResult);
}
} /// <summary>
/// 通过递归获取根目录下的所有子文件夹
/// 适用于无限集
/// 缺点:耗内存
/// </summary>
/// <param name="directoryList">存放所有文件夹的集合</param>
/// <param name="directoryParent">根目录文件夹</param>
public static void GetChildDirectoryByRecursion(List<DirectoryInfo> directoryList, DirectoryInfo directoryParent)
{
DirectoryInfo[] directoryListChild = directoryParent.GetDirectories();
directoryList.AddRange(directoryListChild);
if (directoryListChild.Length > )//跳出条件--->出口
{
foreach (var directoryChild in directoryListChild)
{
GetChildDirectoryByRecursion(directoryList, directoryChild);//相同的代码抽取出来--->递归
}
}
}
}
}
配置路径的新思想:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration; namespace Jungle
{
public class MyConstants
{
/// <summary>
/// 配置绝对路径---模板
/// </summary>
public static string LogPathAbsolute = ConfigurationManager.AppSettings["LogPath"]; /// <summary>
/// 配置相对路径---获取当前程序路径
/// </summary>
public static string LogPathRelative = AppDomain.CurrentDomain.BaseDirectory; /// <summary>
/// 序列化数据地址
/// </summary>
public static string BinarySerializeDataPath = ConfigurationManager.AppSettings["BinarySerializeDataPath"]; //二进制
public static string SoapSerializeDataPath = ConfigurationManager.AppSettings["SoapSerializeDataPath"]; //Soap
public static string XmlSerializeDataPath = ConfigurationManager.AppSettings["XmlSerializeDataPath"]; //Soap
}
}
MyConstants
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings><!-- 每台电脑的路径不一样,可自己更改 -->
<add key="LogPath" value="D:\Coding\Project\Jungle8884\Files\Logs\"/>
<add key="BinarySerializeDataPath" value="D:\Coding\Project\Jungle8884\Files\Serialize\"/>
<add key="SoapSerializeDataPath" value="D:\Coding\Project\Jungle8884\Files\Soap\"/>
<add key="XmlSerializeDataPath" value="D:\Coding\Project\Jungle8884\Files\Xml\"/>
</appSettings>
</configuration>
configuration
Serialize:
using Jungle8884;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization; namespace Jungle
{
/// <summary>
/// 本序列化只作为一个例子
/// 对应于Programmer类
/// 具体情况可以更改为泛型或具体类型
/// </summary>
public class MySerializableHelper
{
/// <summary>
/// 存放文件名称与路径
/// </summary>
private static string sFileNameBinary = Path.Combine(MyConstants.BinarySerializeDataPath, "BinarySerialize.txt");
private static string sFileNameSoap = Path.Combine(MyConstants.SoapSerializeDataPath, "SoapSerialize.txt");
private static string sFileNameXml = Path.Combine(MyConstants.XmlSerializeDataPath, "Programmer.xml"); #region 二进制序列化 public static void BinarySerialize(List<Programmer> pList)
{
using (Stream fStream = new FileStream(sFileNameBinary, FileMode.Create, FileAccess.ReadWrite))
{
pList = DataFactory.BuildProgrammerList();
BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
binFormat.Serialize(fStream, pList);
}
} public static List<Programmer> BinaryDeserialize()
{
List<Programmer> pList = null;
using (Stream fStream = new FileStream(sFileNameBinary, FileMode.Open, FileAccess.ReadWrite))
{
BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
fStream.Position = ;
pList = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化
}
return pList;
} #endregion #region Soap序列化 public static void SoapSerialize(List<Programmer> pList)
{
using (Stream fStream = new FileStream(sFileNameSoap, FileMode.Create, FileAccess.ReadWrite))
{
pList = DataFactory.BuildProgrammerList();
SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
//soapFormat.Serialize(fStream, pList);//SOAP不能序列化泛型对象
soapFormat.Serialize(fStream, pList.ToArray());
}
} public static List<Programmer> SoapDeserialize()
{
List<Programmer> pList = null;
using (Stream fStream = new FileStream(sFileNameSoap, FileMode.Open, FileAccess.ReadWrite))
{
SoapFormatter soapFormat = new SoapFormatter();
fStream.Position = ;
pList = ((Programmer[])soapFormat.Deserialize(fStream)).ToList();
}
return pList;
} #endregion //BinaryFormatter序列化自定义类的对象时,序列化之后的流中带有空字符,以致于无法反序列化,
//反序列化时总是报错“在分析完成之前就遇到流结尾”(已经调用了stream.Seek(0, SeekOrigin.Begin);)。
//改用XmlFormatter序列化之后,可见流中没有空字符,从而解决上述问题,但是要求类必须有无参数构造函数,
//而且各属性必须既能读又能写,即必须同时定义getter和setter,若只定义getter,则反序列化后的得到的各个属性的值都为null。 #region Xml序列化 public static void XmlSerialize(List<Programmer> pList)
{
using (Stream fStream = new FileStream(sFileNameXml, FileMode.Create, FileAccess.ReadWrite))
{
pList = DataFactory.BuildProgrammerList();
XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));
xmlFormat.Serialize(fStream, pList);
}
} public static List<Programmer> XmlDeserialize()
{
List<Programmer> pList = null;
using (Stream fStream = new FileStream(sFileNameXml, FileMode.Open, FileAccess.ReadWrite))
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));
fStream.Position = ;
pList = (List<Programmer>)xmlFormat.Deserialize(fStream);
}
return pList;
} #endregion #region Json序列化分为两种:微软的和Newtonsoft的 //对象到Json字符串叫序列化
public static string JsonSerialize(List<Programmer> pList)
{
pList = DataFactory.BuildProgrammerList();
string sResultJson = MyJsonHelper.ObjectToString<List<Programmer>>(pList);
return sResultJson;
}
public static string JsonSerializeNewtonsoft(List<Programmer> pList)
{
pList = DataFactory.BuildProgrammerList();
string sResultJson = MyJsonHelper.ToJson<List<Programmer>>(pList);
return sResultJson;
} //Json字符串到对象叫反序列化
public static List<Programmer> JsonDeserialize(string sJson)
{
List<Programmer> pList = MyJsonHelper.StringToObject<List<Programmer>>(sJson);
return pList;
}
public static List<Programmer> JsonDeserializeNewtonsoft(string sJson)
{
List<Programmer> pList = MyJsonHelper.ToObject<List<Programmer>>(sJson);
return pList;
}
#endregion }
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;//System.Web.Extensions namespace Jungle
{
public class MyJsonHelper
{ #region 微软自带Json序列化
/// <summary>
/// (Object到)Json的序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">对象实例</param>
/// <returns>返回字符串</returns>
public static string ObjectToString<T>(T obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(obj);
}
/// <summary>
/// Json(到Object)的反序列化
/// </summary>
/// <typeparam name="T">反序列化到对象类型</typeparam>
/// <param name="sContent">待反序列化的字符串</param>
/// <returns></returns>
public static T StringToObject<T>(string sContent)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Deserialize<T>(sContent);
}
#endregion #region Newtonsoft.Json
/// <summary>
/// (Object到)Json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
} /// <summary>
/// (Json到)Object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sContent"></param>
/// <returns></returns>
public static T ToObject<T>(string sContent)
{
return JsonConvert.DeserializeObject<T>(sContent);
}
#endregion }
}
MyJsonHelper
测试代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jungle; namespace Jungle8884
{
class Program
{
static void Main(string[] args)
{
MySafeInvoke.InvokeMethod(() => {
//MyIO.WriteLogsWriteLine("Get up to cheer up!");
//MyIO.WriteLogsAppendText("睡你麻痹,起来嗨!");
//MyIO.WriteLogsAppendText("为什么?");
//MyIO.WriteLogsAppendText("你很帅啊!");
//MyIO.WriteLogsAppendText("真的!");
//MyIO.WriteLogsAppendText("我不信...");
//MyIO.WriteLogsAppendText("这是真的!");
//MyIO.WriteLogsAppendText("这不是梦!");
//MyIO.ReadLogsToConsole();
//MyIO.ReadLargeFileToConsole();
//Process.Start(Path.Combine(MyConstants.LogPathAbsolute, "Log.txt"));//打开文本文件
List<Programmer> pList = null;
MySerializableHelper.BinarySerialize(pList);
MySerializableHelper.SoapSerialize(pList);
MySerializableHelper.XmlSerialize(pList);
});
}
}
}
下载链接:
链接:https://pan.baidu.com/s/1mjNnqQ0 密码:pco3
IO&&Serize 利用线程Thread.Sleep实现"自动输出"的更多相关文章
- 利用javascript实现文本的自动输出
主要利用了setTimeout(),递归和String.substring(); 做出的效果就像是有一个打字员在打字. <!doctype html> <html lang=&quo ...
- RabbitMQ/JAVA 客户端测试(补:利用线程)
上次进行了简单的连接测试.这次主要进行一下小小的补充.利用线程将生产者消费者代码合到一个文件中. 我是将Recv.java(消费者)文件放在一个线程里添加到Send.java(生产者)中. 代码如下: ...
- 线程(thread)
线程(thread): 现代操作系统引入进程概念,为了并发(行)任务 1.进程之间的这种切换代价很高 2.通信方式的代价也很大基本概念: 1.线程是比进程更小的资源单位,它是进程中的一个执行路线(分支 ...
- 线程 Thread Runnable 守护线程 join MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- 转:线程Thread (1)
引言 1.理解多线程 2. 线程异步与线程同步 3.创建多线程应用程序 3.1通过System.Threading命名空间的类构建 3.1.1异步调用线程 3.1.2并发问题 3.1.3线程同步 3. ...
- 多个线程分别顺序交替打印一种不同字符abcdefg(已实现随便多少个线程打印多少个字符,利用线程池实现多线程)
下面实现多线程顺序打印字符"abcdefg": 实现Runnable接口: /** * @author: rhyme * @date: 2019-08-17 14:39 * @to ...
- Python 线程,with的作用(自动获取和释放锁Lock)
Python 线程,with的作用(自动获取和释放锁Lock) import threading import time num= #全局变量多个线程可以读写,传递数据 mutex=threading ...
- C/C++ Muti-Thread多线程编程学习(之)线程Thread | 创建、运行、结束
文章目录 前言 线程 Thread 创建线程 CreateThread _beginthread _beginthreadex pthread_create 线程运行 结束线程 前言 多线程(Mu ...
- 1.利用consul实现k8s服务自动发现
标题 : 1.利用consul实现k8s服务自动发现 目录 : 微服务架构设计 序号 : 1 ] } } ] } } - consul自身支持ACL,但目前,Helm图表不支持其中一些功能,需要额 ...
随机推荐
- c# excel 导入 与 导出(可直接用)
c#操作excel方式很多 采用OleDB读取EXCEL文件: 引用的com组件:Microsoft.Office.Interop.Excel.dll 读取EXCEL文件 将EXCEL文件转化成C ...
- FSFS和VDFS存储方式的区别
简单来说这个是VisualSVN基于FSFS文件系统格式扩展的.也就是说,分布式版本管理DVCS兴起之后,大家发现多个仓库的好处了,开始给SVN增加这个功能. 至于FSFS本身是SVN在2004年开始 ...
- 宝塔linux面板.txt
安装命令: yum -y install screen wget && screen -S bt wget -O install.sh http://103.224.251.79:58 ...
- phpmailer的SMTP ERROR: Failed to connect to server: 10
请问,我在win7上学习使用phpmailer时,出现这种错误怎么处理啊? SMTP ERROR: Failed to connect to server: (0) SMTP connect() fa ...
- ip 淘宝ip库 精简版
<?php header('Content-type: text/html; charset=utf-8'); //根据ip获取城市.网络运营商等信息 function findCityByIp ...
- [机器学习]-[数据预处理]-中心化 缩放 KNN(二)
上次我们使用精度评估得到的成绩是 61%,成绩并不理想,再使 recall 和 f1 看下成绩如何? 首先我们先了解一下 召回率和 f1. 真实结果 预测结果 预测结果 正例 反例 正例 TP 真 ...
- ntp 时钟同步
注意: 如果你无法和外部网络的时钟同步,请检查UDP端口时候被封.
- python实现端口扫描器/DoS/DDoS
整理github,梳理下Python小工具.以下是python实现的DoS/DDoS/端口扫描器(github). 一.DoS SYN Flood是当前最流行的DoS(拒绝服务攻击)与DdoS(分布式 ...
- JDK自带的日志Logging
OK,现在我们来研究下JDK自带的日志Logger. 从jdk1.4起,JDK开始自带一套日志系统.JDK Logger最大的优点就是不需要任何类库的支持,只要有Java的运行环境就可以使用. 相对于 ...
- json_encode详解
<?php $json = Array ( "a" => "php" , "b" => "mysql" ...