IO&Seralize

IO

 1 <appSettings>
 2     <!--日志路径-->
 3     <add key="LogPath" value="E:\学习\C#进阶\fsociety\fSociety0\Logs\Log\"/>
 4     <add key="LogMovePath" value="E:\学习\C#进阶\fsociety\fSociety0\Logs\LogMove\"/>
 5     <!--<add key="LogPath" value="D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\Log\"/>
 6     <add key="LogMovePath" value="D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\LogMove\"/>
 7     <add key="ImagePath" value="D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\Image\"/>-->
 8     <add key="VerifyPath" value="D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\Image\"/>
 9     <add key="CurrentDataPath" value="D:\ruanmou\online7\20161014Advanced7Course6IOSerialize\IOSerialize\IOSerialize\File\"/>
10   </appSettings>

appSettings

1         /// <summary>
2         /// 配置绝对路径
3         /// </summary>
4         private static string LogPath = ConfigurationManager.AppSettings["LogPath"];
5         private static string LogMovePath = ConfigurationManager.AppSettings["LogMovePath"];
6         /// <summary>
7         /// 获取当前程序路径
8         /// </summary>
9         private static string LogPath2 = AppDomain.CurrentDomain.BaseDirectory;       
Directory
1        {//Directory
2                 bool isExists = Directory.Exists(LogPath);
3                 if (!isExists)
4                 {
5                     DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath);//一次性创建全部的子路径
6                     Directory.Move(LogPath, LogMovePath);//移动  原文件夹就不在了
7                     Directory.Delete(LogMovePath);//删除
8                 }
9             }

File

 1         {//File
 2                 string fileName = Path.Combine(LogPath, "log.txt");
 3                 string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
 4                 string fileNameMove = Path.Combine(LogPath, "logMove.txt");
 5                 bool isExists = File.Exists(fileName);
 6                 if (!isExists)
 7                 {
 8                     Directory.CreateDirectory(LogPath);
 9                     using (FileStream stream = File.Create(fileName))//创建文件并写入
10                     {
11                         string name = "12345567778890";
12
13                         byte[] bytes = Encoding.Default.GetBytes(name);
14                         stream.Write(bytes, 0, bytes.Length);
15                         stream.Flush();
16                     }
17
18                     string msg = "今天是Course6IOSerialize,今天上课的人有26个人";
19                     using (StreamWriter sw = File.AppendText(fileName))
20                     {
21                         sw.WriteLine(msg);
22                         sw.Flush();
23                     }
24
25                     foreach (string result in File.ReadAllLines(fileName))
26                     {
27                         Console.WriteLine(result);
28                     }
29                     File.ReadAllText(fileName);
30                     File.ReadAllBytes(fileName);
31
32                     using (FileStream stream = File.OpenRead(fileName))//分批读取
33                     {
34                         int length = 5;
35                         int result = 0;
36
37                         do
38                         {
39                             byte[] bytes = new byte[length];
40                             result = stream.Read(bytes, 0, 5);
41                             for (int i = 0; i < result; i++)
42                             {
43                                 Console.WriteLine(bytes[i].ToString());
44                             }
45                         }
46                         while (length == result);
47                     }
48
49                     File.Copy(fileName, fileNameCopy);
50                     File.Move(fileName, fileNameMove);
51                     File.Delete(fileNameCopy);
52                     File.Delete(fileNameMove);
53
54                 }
55             }

Log

 1         public static void Log(string msg)
 2         {
 3             StreamWriter sw = null;
 4             try
 5             {
 6                 string fileName = "log.txt";
 7                 string totalPath = Path.Combine(LogPath, fileName);
 8                 //int i = 0;
 9
10                 //int result = 5 / i;
11
12                 if (Directory.Exists(LogPath))
13                 {
14                     if (File.Exists(totalPath))
15                         sw = File.AppendText(totalPath);
16                     else
17                         sw = File.CreateText(totalPath);
18                 }
19                 else
20                 {
21                     Directory.CreateDirectory(LogPath);
22                     sw = File.CreateText(totalPath);
23                 }
24                 sw.WriteLine(string.Format("{0}:{1}", DateTime.Now, msg));
25                 sw.WriteLine("***************************************************");
26             }
27             catch (Exception ex)
28             {
29                 Console.WriteLine(ex.Message);//log
30                 //throw ex;
31                 //throw new exception("这里异常");
32             }
33             finally
34             {
35                 if (sw != null)
36                 {
37                     sw.Flush();
38                     sw.Close();
39                     sw.Dispose();
40                 }
41             }
42         }    

Log

 1     public class Recursion
 2     {
 3         public static List<DirectoryInfo> FindAll(string rootPath)
 4         {
 5             List<DirectoryInfo> dirList = new List<DirectoryInfo>();
 6             DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);//1
 7             dirList.Add(rootDirectory);
 8             FindChild(rootDirectory, dirList);
 9
10             return dirList;
11         }
12
13         /// <summary>
14         /// 找出文件夹的子文件夹,放入集合,
15         /// 遍历子文件,再。。。。
16         /// </summary>
17         /// <param name="parentDirectory">文件夹</param>
18         /// <param name="dirList">集合</param>
19         private static void FindChild(DirectoryInfo parentDirectory, List<DirectoryInfo> dirList)
20         {
21             DirectoryInfo[] dirChildList = parentDirectory.GetDirectories();
22             dirList.AddRange(dirChildList);
23             if (dirChildList != null && dirChildList.Length > 0)//1 递归一定要有跳出条件
24             {
25                 foreach (var child in dirChildList)//2 递归很耗资源
26                 {
27                     FindChild(child, dirList);
28                 }
29             }
30         }
31     }

Recursion

 1         private static List<Programmer> GetProgrammerList()
 2         {
 3             List<Programmer> list = new List<Programmer>();
 4             list.Add(new Programmer()
 5             {
 6                 Name = "快乐阳光",
 7                 Sex = "男"
 8             });
 9             list.Add(new Programmer()
10             {
11                 Name = "荼蘼",
12                 Sex = "女"
13             });
14             list.Add(new Programmer()
15             {
16                 Name = "笑对人生",
17                 Sex = "男"
18             });
19             list.Add(new Programmer()
20             {
21                 Name = "yizi",
22                 Sex = "男"
23             });
24             list.Add(new Programmer()
25             {
26                 Name = "萌萌的",
27                 Sex = "男"
28             });
29             list.Add(new Programmer()
30             {
31                 Name = "红领巾",
32                 Sex = "男"
33             });
34             list.Add(new Programmer()
35             {
36                 Name = "net",
37                 Sex = "男"
38             });
39             return list;
40         }

List

Serialize

 1         /// <summary>
 2         /// JavaScriptSerializer
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="obj"></param>
 6         /// <returns></returns>
 7         public static string ObjectToString<T>(T obj)
 8         {
 9             JavaScriptSerializer jss = new JavaScriptSerializer();
10             return jss.Serialize(obj);
11         }
12
13         /// <summary>
14         /// JavaScriptSerializer
15         /// </summary>
16         /// <typeparam name="T"></typeparam>
17         /// <param name="content"></param>
18         /// <returns></returns>
19         public static T StringToObject<T>(string content)
20         {
21             JavaScriptSerializer jss = new JavaScriptSerializer();
22             return jss.Deserialize<T>(content);
23         }
24
25         /// <summary>
26         /// JsonConvert.SerializeObject
27         /// </summary>
28         /// <typeparam name="T"></typeparam>
29         /// <param name="obj"></param>
30         /// <returns></returns>
31         public static string ToJson<T>(T obj)
32         {
33             return JsonConvert.SerializeObject(obj);
34         }
35
36         /// <summary>
37         /// JsonConvert.DeserializeObject
38         /// </summary>
39         /// <typeparam name="T"></typeparam>
40         /// <param name="content"></param>
41         /// <returns></returns>
42         public static T ToObject<T>(string content)
43         {
44             return JsonConvert.DeserializeObject<T>(content);
45         }        

JavaScriptSerializer

 1        public static string ToXml<T>(T t) where T : new()
 2         {
 3             string fileName = @"E:\online_3\20150806第三期高级班Course10SerializeJson\Course10SerializeJson\Course10SerializeJson\file\Person.xml";//文件名称与路径
 4             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 5             {
 6                 XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
 7                 xmlFormat.Serialize(fStream, t);
 8             }
 9             string[] lines = File.ReadAllLines(fileName);
10             return string.Join("", lines);
11         }
12
13         public static T ToObject<T>() where T : new()
14         {
15             string fileName = @"E:\online_3\20150806第三期高级班Course10SerializeJson\Course10SerializeJson\Course10SerializeJson\file\Person.xml";//文件名称与路径
16             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
17             {
18                 XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
19                 return (T)xmlFormat.Deserialize(fStream);
20             }
21         }    

XmlSerializer

 1         private static string CurrentDataPath = ConfigurationManager.AppSettings["CurrentDataPath"];
 2         public static void BinarySerialize()
 3         {
 4             //使用二进制序列化对象
 5             string fileName = Path.Combine(CurrentDataPath, @"BinarySerialize.txt");//文件名称与路径
 6             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 7             {
 8                 List<Programmer> pList = GetProgrammerList();
 9                 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
10                 binFormat.Serialize(fStream, pList);
11             }
12             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
13             {
14                 List<Programmer> pList = new List<Programmer>();
15                 BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
16                 //使用二进制反序列化对象
17                 pList.Clear();//清空列表
18                 fStream.Position = 0;//重置流位置
19                 pList = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化对象
20             }
21         }    

BinaryFormatter

 1  public static void SoapSerialize()
 2         {
 3             //使用Soap序列化对象
 4             string fileName = Path.Combine(CurrentDataPath, @"SoapSerialize.txt");//文件名称与路径
 5             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 6             {
 7                 List<Programmer> pList = GetProgrammerList();
 8                 SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
 9                 //soapFormat.Serialize(fStream, list);//SOAP不能序列化泛型对象
10                 soapFormat.Serialize(fStream, pList.ToArray());
11             }
12             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
13             {
14                 SoapFormatter soapFormat = new SoapFormatter();//创建二进制序列化器
15                 //使用二进制反序列化对象
16                 fStream.Position = 0;//重置流位置
17                 List<Programmer> pList = ((Programmer[])soapFormat.Deserialize(fStream)).ToList();//反序列化对象
18             }
19         }

SoapFormatter

 1         public static void XmlSerialize()
 2         {
 3             //使用XML序列化对象
 4             string fileName = Path.Combine(CurrentDataPath, @"Student.xml");//文件名称与路径
 5             using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
 6             {
 7                 List<Programmer> pList = GetProgrammerList();
 8                 XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型
 9                 xmlFormat.Serialize(fStream, pList);
10             }
11             using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
12             {
13                 List<Programmer> pList = new List<Programmer>();
14                 XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//创建XML序列化器,需要指定对象的类型
15                 //使用XML反序列化对象
16                 fStream.Position = 0;//重置流位置
17                 pList = (List<Programmer>)xmlFormat.Deserialize(fStream);
18             }
19         }

XmlSerializer

时间: 2024-08-06 00:58:07

IO&Seralize的相关文章

10.6 监控io性能 - 10.7 free命令 - 10.8 ps命令 - 10.9 查看网络状态 - 10.10 linux下抓包

- 10.6 监控io性能 - 10.7 free命令 - 10.8 ps命令 - 10.9 查看网络状态 - 10.10 linux下抓包 - 扩展tcp三次握手四次挥手 http://www.doc88.com/p-9913773324388.html  - tshark几个用法:http://www.aminglinux.com/bbs/thread-995-1-1.html  # 10.6 监控io性能 ![mark](http://oqxf7c508.bkt.clouddn.com/b

JavaSE8基础 File createNewFile 在一个不存在的文件夹中创建文件时 会抛IO异常(绝对路径)

os :windows7 x64    jdk:jdk-8u131-windows-x64    ide:Eclipse Oxygen Release (4.7.0) information: 在编写代码时,javase8文件夹的情况截图. code: package jizuiku0; import java.io.File; import java.io.IOException; /* * @version V17.09 */ public class FileDemo_1 { public

Performance Monitor4:监控SQL Server的IO性能

SQL Server的IO性能受到物理Disk的IO延迟和SQL Server内部执行的IO操作的影响.在监控Disk性能时,最主要的度量值(metric)是IO延迟,IO延迟是指从Application创建IO请求,到Disk完成IO请求的时间延迟.如果物理Disk不能及时完成IO请求,跟不上请求负载的速度,那么SQL Server就容易出现性能问题.SQL Server内部在执行一些特定的操作时,会和Disk做读写交互,这也会影响物理硬盘响应SQL Server的IO请求的性能,使查询进程处

对IO流的操作(文件大小,拷贝,移动,删除)

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.SequenceInputStream; class LjyFileClass { /*LjyFileClass工具类使用需知: * * 1.计算

java IO之输入流——InputStream

java的基本输入流是java.io.InputStream,该抽象类定义了输入流的基本输入操作方法,实现自该抽象类的子类都有定义自己的数据源,例如ByteArrayInputStream的构造函数指定了ByteArrayInputStream输入流的数据源必须是一个字符数组.这就可以有多种不同的数据源,包括:字符数组.String对象.文件."管道".一个由其他种类的流组成的序列... 1 public ByteArrayInputStream(byte buf[]) {} 2 3

Hive报错 Failed with exception java.io.IOException:java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: ${system:user.name%7D

报错信息如下 Failed with exception java.io.IOException:java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: ${system:user.name%7D 解决方法: 编辑 hive-site.xml 文件,添加下边的属性 <property> <name>system:java.io.tmpdir<

Linux 性能监控 : CPU 、Memory 、 IO 、Network

一.CPU 1.良好状态指标 CPU利用率:User Time <= 70%,System Time <= 35%,User Time + System Time <= 70% 上下文切换:与CPU利用率相关联,如果CPU利用率状态良好,大量的上下文切换也是可以接受的 可运行队列:每个处理器的可运行队列<=3个线程 2.监控工具 vmstat $ vmstat 1 procs -----------memory---------- ---swap-- -----io---- --s

《linux 内核全然剖析》 include/asm/io.h

include/asm/io.h #define outb(value,port) __asm__ ("outb %%al,%%dx"::"a" (value),"d" (port)) //宏定义outb用汇编实现了在端口地址port处写入值value //使用的寄存器是al,一个byte长度,而端口port使用的是2byte长度地址来标记的寄存器,注意这里寄存器的使用 #define inb(port) ({ unsigned char _v;

Python有了asyncio和aiohttp在爬虫这类型IO任务中多线程/多进程还有存在的必要吗?

最近正在学习Python中的异步编程,看了一些博客后做了一些小测验:对比asyncio+aiohttp的爬虫和asyncio+aiohttp+concurrent.futures(线程池/进程池)在效率中的差异,注释:在爬虫中我几乎没有使用任何计算性任务,为了探测异步的性能,全部都只是做了网络IO请求,就是说aiohttp把网页get完就程序就done了. 结果发现前者的效率比后者还要高.我询问了另外一位博主,(提供代码的博主没回我信息),他说使用concurrent.futures的话因为我全