码迷,mamicode.com
首页 > 其他好文 > 详细

(转)txt读写 操作封装

时间:2015-12-20 19:14:22      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

[code]csharpcode:

using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
public class TextCreatWrite : MonoBehaviour {

	/// <summary>
	/// 判断一个文件是否存在.
	/// </summary>
	/// <returns><c>true</c>, if exists was filed, <c>false</c> otherwise.</returns>
	/// <param name="path">Path.</param>
	public static bool FileExists(string path)
	{
		if(File.Exists(path))
			//存在
			return true;
		else
			//不存在
			return false;
	}

	/// <summary>
	/// 创建一个文件,文件存在就不创建.
	/// </summary>
	/// <param name="path">Path.</param>
	public static void CreatFile(string path)
	{
		if (FileExists (path))   //文件已经存在就返回.
			return;
		// 如果文件不存在,创建文件; 如果存在,覆盖文件
		StreamWriter sw2 = new StreamWriter(path, false, Encoding.UTF8);
		sw2.Close ();
	}

	/// <summary>
	/// 在文件末尾追加写入数据,然后在数据后面添加换行符.
	/// </summary>
	/// <param name="path">路径.</param>
	/// <param name="date">要写入的字符串.</param>
	public static void AppendTextAddLineFeed(string path,string date)
	{
		// true 是 append text, false 为覆盖原文件
		StreamWriter sw2 = new StreamWriter(path, true, Encoding.UTF8);
		sw2.WriteLine (date);
		sw2.Close ();
	}


	/// <summary>
	///表示换行符的string.
	/// </summary>
	/// <returns>The line feed.</returns>
	public static string GetLineFeed()
	{
		//utf-8里换行的十六进制是 0d 0a
		//用转义字符表示\n\r
		int value1 = Convert.ToInt32("0D", 16);
		int value2 = Convert.ToInt32("0A", 16);
		string stringValue = Char.ConvertFromUtf32(value1);
		stringValue+=Char.ConvertFromUtf32(value2);
		return stringValue;
	}

	/// <summary>
	/// 把16进制转成string格式.
	/// </summary>
	/// <returns>The tostring.</returns>
	/// <param name="str16">要转换的16进制字符,比如"0d"是回车.</param>
	static public string ConvertHex16To_string(string str16)
	{
		int value1 = Convert.ToInt32(str16, 16);
		string stringValue = Char.ConvertFromUtf32(value1);
		return stringValue;
	}

	/// <summary>
	/// 16进制转char.
	/// </summary>
	/// <returns>The to char.</returns>
	/// <param name="str16">要转换的16进制字符,比如"0d"是回车".</param>
	static public char ConvertHex16ToChar(string str16)
	{
		int value1 = Convert.ToInt32(str16, 16);
		return (char)value1;
	}

	/// <summary>
	/// 读取文件,返回每行数据集合List<string>.
	/// </summary>
	/// <returns>The all lines.</returns>
	/// <param name="path">路径.</param>
	static public List<string> ReadAllLines(string path)
	{
		// 也可以指定编码方式
		string[] strs2 = File.ReadAllLines(path, Encoding.UTF8);
		return new List<string> (strs2);
	}
}

 

(转)txt读写 操作封装

标签:

原文地址:http://www.cnblogs.com/backlighting/p/5061510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!