对文件的读写,读写文本文件

最近需要对一个文件进行数量的分割,因为数据量庞大,所以就想到了通过写程序来处理。将代码贴出来以备以后使用。

static public string Read(string path)
{
StreamReader sr = new StreamReader(path,Encoding.Default);
String line;
StringBuilder sb=new StringBuilder();
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);

//读取文件的内容 放置于StringBuilder 中

}
return sb.ToString();

StreamReader sr = new StreamReader(path, Encoding.Default);
String line;
StringBuilder sb = new StringBuilder();

}

while ((line = sr.ReadLine()) != null)
{
sb.Append(line);
}

 

 

 

//然后将其装换为泛型对象 

public static string ReadFile(string FilePath)
{
if (System.IO.File.Exists(FilePath))
{
try
{
StreamReader reader = new StreamReader(FilePath,
Encoding.GetEncoding(“gb2312”));//System.IO.File.OpenText(FilePath);
StringBuilder builder = new StringBuilder();
string str = “”;
string str2 = “”;
while ((str = reader.ReadLine()) != null)
{
builder.AppendLine(str  );
}
str2 = builder.ToString();
reader.Close();
return str2;
}
catch
{
return “”;
}
}
return “”;
}

JavaScriptSerializer js = new JavaScriptSerializer();
Models.aa a = js.Deserialize<aa>(sb.ToString());
List<aaa> aa = a.dateils;

 

图片 1

public static bool SaveFile(string FilePath, string type, string
content)
{
string path = FilePath;
if (!File.Exists(path))
type = “NEW”;
try
{
StreamWriter writer;
if (type == “NEW”)
{
using (writer = new StreamWriter(FilePath, false,
Encoding.GetEncoding(“gb2312”)))//System.IO.File.CreateText(path))
{
writer.Write(content);
writer.Flush();
writer.Close();
return true;
}
}
if (type == “ADD”)
{
if (System.IO.File.Exists(path))
{
writer = new StreamWriter(path, true, Encoding.GetEncoding(“gb2312”));
writer.Write(content);
writer.Flush();
writer.Close();
return true;
}
return false;
}
return false;
}
catch
{
return false;
}
}

//然后在通过foreach来遍历泛型 从来达到指定数量的分组
文章中分组的数量为100

 

图片 2

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注