IOHelper(自制常用的输入输出的帮助类)

常用的读写文件,和地址转换(win和linux均支持),操作文件再也不是拼接那么的low了

using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace Cactus.Common
{
    /// <summary>
    /// 常用IO操作类
    /// </summary>
    public class IOHelper
    {
        /// <summary>
        /// 系统路径转换为web路径地址
        /// </summary>
        /// <param name="fullPath">文件完整地址</param>
        /// <param name="AppPath">应用地址</param>
        /// <param name="dHear">是否去掉首部的分隔符</param>
        /// <returns></returns>
        public static string WebPathParse(string fullPath,string appPath,bool dHear)
        {
            string sys = Path.DirectorySeparatorChar.ToString();
            string web = @"/";//web的分隔符
            if (fullPath.StartsWith(appPath))
            {
                string webPath = fullPath.Remove(0, appPath.Length);
                webPath = webPath.Replace(sys, web);
                if (webPath.StartsWith(web) == false)
                {
                    webPath = web + webPath;
                }
                if (dHear)
                {
                    webPath = IOHelper.RemoveHead(webPath, web);
                }
                return webPath;
            }
            else {
                return "";
            }
        }
        /// <summary>
        /// web路径地址转换为系统路径
        /// </summary>
        /// <param name="appPath">应用路径</param>
        /// <param name="webPath">web路径</param>
        /// <param name="dHear">是否去掉首部的路径分隔符</param>
        /// <returns></returns>
        public static string SysPathParse(string appPath, string webPath, bool dHear)
        {
            string sys = Path.DirectorySeparatorChar.ToString();
            string web = @"/";//web的分隔符
            webPath = webPath.Replace(web, sys);
            if (dHear)
            {
                webPath = IOHelper.RemoveHead(webPath, sys);
            }
            string result="";
            if (appPath.EndsWith(sys))
            {
                if (webPath.StartsWith(sys))
                {
                    result = appPath + webPath.Remove(0,1);
                }
                else
                {
                    result = appPath + webPath;
                }
            }
            else {
                if (webPath.StartsWith(sys))
                {
                    result = appPath + webPath;
                }
                else {
                    result = appPath + sys + webPath;
                }
            }
            return result;
        }
        /// <summary>
        /// 路径解析转换,转化成符合当前系统的路径符号
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="flag">(路径的类型)1:windows \ 2:linux /(linux和web网页的分隔相符)</param>
        /// <param name="dHear">是否去掉首部的路径分隔符</param>
        /// <returns></returns>
        public static string PathParse(string path, int flag, bool dHear)
        {
            string win = @"\";
            string linux = @"/";
            string sys=Path.DirectorySeparatorChar.ToString();
            if (flag == 1)
            {
                path = path.Replace(win, sys);
            }
            else if (flag == 2)
            {
                path = path.Replace(linux, sys);
            }
            if (dHear) {
                path = IOHelper.RemoveHead(path, sys);
            }
            return path;
        }
        /// <summary>
        /// (递归)去掉所有首部出现的字符串
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="headStr">首部出现的字符串</param>
        /// <returns></returns>
        public static string RemoveHead(string str, string headStr)
        {
            if (str.StartsWith(headStr))
            {
                str = str.Remove(0, headStr.Length);
                return RemoveHead(str, headStr);
            }
            else {
                return str;
            }
        }

        /// <summary>
        /// 返回指定目录下目录信息
        /// </summary>
        /// <param name="strDirectory">路径</param>
        /// <returns></returns>
        public static DirectoryInfo[] GetDirectory(string strDirectory)
        {
            if (string.IsNullOrEmpty(strDirectory) == false)
            {
                return new DirectoryInfo(strDirectory).GetDirectories();
            }
            return new DirectoryInfo[] { };
        }
        /// <summary>
        /// 返回指定目录下所有文件信息
        /// </summary>
        /// <param name="strDirectory">路径</param>
        /// <returns></returns>
        public static FileInfo[] GetFiles(string strDirectory)
        {
            if (string.IsNullOrEmpty(strDirectory) == false)
            {
                return new DirectoryInfo(strDirectory).GetFiles();
            }
            return new FileInfo[] { };
        }
        /// <summary>
        ///  返回指定目录下过滤文件信息
        /// </summary>
        /// <param name="strDirectory">目录地址</param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static FileInfo[] GetFiles(string strDirectory, string filter)
        {
            if (string.IsNullOrEmpty(strDirectory) == false)
            {
                return new DirectoryInfo(strDirectory).GetFiles(filter, SearchOption.TopDirectoryOnly);
            }
            return new FileInfo[] { };
        }
        /// <summary>
        /// debug输出
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteDebug(Exception ex)
        {
            Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Debug.WriteLine("Data:" + ex.Data + Environment.NewLine
            + " InnerException:" + ex.InnerException + Environment.NewLine
            + " Message:" + ex.Message + Environment.NewLine
            + " Source:" + ex.Source + Environment.NewLine
            + " StackTrace:" + ex.StackTrace + Environment.NewLine
            + " TargetSite:" + ex.TargetSite);
        }
        /// <summary>
        /// 控制台数据错误
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteConsole(Exception ex)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine("Data:" + ex.Data + Environment.NewLine
            + " InnerException:" + ex.InnerException + Environment.NewLine
            + " Message:" + ex.Message + Environment.NewLine
            + " Source:" + ex.Source + Environment.NewLine
            + " StackTrace:" + ex.StackTrace + Environment.NewLine
            + " TargetSite:" + ex.TargetSite);
        }
        /// <summary>
        /// 错误记录
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteLog(Exception ex)
        {
            WriteLog(ex,null);
        }
        /// <summary>
        /// 错误记录
        /// </summary>
        /// <param name="ex">错误信息</param>
        /// <param name="appendInfo">追加信息</param>
        public static void WriteLog(Exception ex, string appendInfo) {
            if (string.IsNullOrEmpty(appendInfo))
            {
                WriteLog("Data:" + ex.Data + Environment.NewLine
            + " InnerException:" + ex.InnerException + Environment.NewLine
            + " Message:" + ex.Message + Environment.NewLine
            + " Source:" + ex.Source + Environment.NewLine
            + " StackTrace:" + ex.StackTrace + Environment.NewLine
            + " TargetSite:" + ex.TargetSite);
            }
            else {
                WriteLog("Data:" + ex.Data + Environment.NewLine
            + " InnerException:" + ex.InnerException + Environment.NewLine
            + " Message:" + ex.Message + Environment.NewLine
            + " Source:" + ex.Source + Environment.NewLine
            + " StackTrace:" + ex.StackTrace + Environment.NewLine
            + " TargetSite:" + ex.TargetSite + Environment.NewLine
            + " appendInfo:" + appendInfo);
            }
        }
        /// <summary>
        /// 写log
        /// </summary>
        /// <param name="InfoStr"></param>
        public static void WriteLog(string InfoStr)
        {
            WriteLog(InfoStr, AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "Log");
        }
        /// <summary>
        /// 写log(自动时间log)
        /// </summary>
        /// <param name="InfoStr">内容</param>
        /// <param name="FilePath">目录地址</param>
        public static void WriteLog(string InfoStr, string DirPath)
        {
            WriteLog(InfoStr, DirPath, Encoding.UTF8);
        }
        /// <summary>
        /// 写log(自动时间log)
        /// </summary>
        /// <param name="InfoStr">内容</param>
        /// <param name="DirPath">目录地址</param>
        /// <param name="encoding">编码</param>
        public static void WriteLog(string InfoStr, string DirPath, Encoding encoding)
        {
            FileStream stream = null;
            System.IO.StreamWriter writer = null;
            try
            {
                string logPath = DirPath;
                if (Directory.Exists(logPath) == false)
                {
                    Directory.CreateDirectory(logPath);
                }
                string filepath = logPath + Path.DirectorySeparatorChar + "log_" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
                if (File.Exists(filepath) == false)
                {
                    stream = new FileStream(filepath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                }
                else
                {
                    stream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }
                writer = new System.IO.StreamWriter(stream, encoding);
                writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                writer.WriteLine(InfoStr);
                writer.WriteLine("");
            }
            finally
            {
                if (writer != null)
                {
                    //writer.Close();
                    writer.Dispose();
                }
                //if (stream != null)
                //{
                //    //stream.Close();
                //    stream.Dispose();
                //}
            }
        }

        /// <summary>
        /// 写log到指定文件(不存在就创建)
        /// </summary>
        /// <param name="InfoStr">内容</param>
        /// <param name="FilePath">文件地址</param>
        public static void WriteLogToFile(string InfoStr, string FilePath)
        {
            WriteLogToFile(InfoStr, FilePath,Encoding.UTF8);
        }
        /// <summary>
        /// 写log到指定文件(不存在就创建)
        /// </summary>
        /// <param name="InfoStr">内容</param>
        /// <param name="FilePath">文件地址</param>
        /// <param name="encoding">编码</param>
        public static void WriteLogToFile(string InfoStr, string FilePath, Encoding encoding)
        {
            FileStream stream = null;
            System.IO.StreamWriter writer = null;
            try
            {
                string logPath = FilePath;
                if (File.Exists(logPath) == false)
                {
                    stream = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                }
                else
                {
                    stream = new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }

                writer = new System.IO.StreamWriter(stream, encoding);
                writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                writer.WriteLine(InfoStr);
                writer.WriteLine("");
            }
            finally
            {
                if (writer != null)
                {
                    //writer.Close();
                    writer.Dispose();
                }
                //if (stream != null)
                //{
                //    //stream.Close();
                //    stream.Dispose();
                //}
            }
        }
        /// <summary>
        /// 写内容到指定文件(不存在就创建)
        /// </summary>
        /// <param name="InfoStr">内容</param>
        /// <param name="FilePath">文件地址</param>
        /// <param name="encoding">编码</param>
        /// <param name="append">是否追加</param>
        public static void WriteInfoToFile(string InfoStr, string FilePath, Encoding encoding,bool append)
        {
            FileStream stream = null;
            System.IO.StreamWriter writer = null;
            try
            {
                string logPath = FilePath;
                if (File.Exists(logPath) == false)
                {
                    stream = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                    writer = new System.IO.StreamWriter(stream, encoding);
                }
                else
                {
                    //存在就覆盖
                    writer = new System.IO.StreamWriter(logPath, append, encoding);
                }
                writer.Write(InfoStr);
            }
            finally
            {
                if (writer != null)
                {
                    //writer.Close();
                    writer.Dispose();
                }
                //if (stream != null)
                //{
                //    //stream.Close();
                //    stream.Dispose();
                //}
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="InfoStr"></param>
        /// <param name="FilePath"></param>
        /// <param name="encoding"></param>
        public static void WriteInfoToFile(string InfoStr, string FilePath, Encoding encoding) {
            WriteInfoToFile(InfoStr, FilePath, encoding,false);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="InfoStr"></param>
        /// <param name="FilePath"></param>
        public static void WriteInfoToFile(string InfoStr, string FilePath)
        {
            WriteInfoToFile(InfoStr, FilePath, Encoding.UTF8, false);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="datagram"></param>
        /// <param name="FilePath"></param>
        /// <param name="callback"></param>
        /// <param name="numBytes"></param>
        public static void AsyncWriteLog(byte[] datagram, string FilePath, AsyncCallback callback, int numBytes)
        {
            FileStream stream = null;
            try
            {
                string logPath = FilePath;
                if (File.Exists(logPath) == false)
                {
                    stream = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                }
                else
                {
                    stream = new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                }

                if (stream.CanWrite)
                {

                    stream.BeginWrite(datagram, 0, numBytes, callback, "AsyncWriteLog_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else
                {
                    throw new Exception("文件无法写入,文件或只读!");
                }
            }
            finally
            {
                if (stream != null)
                {
                    //stream.Close();
                    stream.Dispose();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="datagram"></param>
        /// <param name="FilePath"></param>
        /// <param name="numBytes"></param>
        public static void AsyncWriteLog(byte[] datagram, string FilePath, int numBytes)
        {
            AsyncWriteLog(datagram, FilePath, new AsyncCallback(AsyncCallbackFunc), numBytes);
        }
        public static void AsyncCallbackFunc(IAsyncResult result)
        {
            FileStream filestream = result.AsyncState as FileStream;
            filestream.EndWrite(result);
            filestream.Close();
        }

        /// <summary>
        /// 文本转义(方便讲文本转换成C#变量代码)
        /// 例子 " 转化成 string str="\"";
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToEscape(string str, string m_var)
        {
            /*
                "           \"
                \           \            */
            str = str.Trim();
            str = str.Replace("\\", "\\\\");
            str = str.Replace("\"", "\\\"");
            return "string " + m_var + "=\"" + str + "\";";
        }
        public static string ReadTxt(string filePath) {
            return ReadTxt(filePath, Encoding.UTF8);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="enc"></param>
        /// <returns></returns>
        public static string ReadTxt(string filePath, Encoding enc) {
            FileStream stream = null;
            System.IO.StreamReader reader = null;
            string result = "";
            try
            {
                if (File.Exists(filePath) == false)
                {
                    stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Read, FileShare.ReadWrite);
                }
                else
                {
                    stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    reader = new System.IO.StreamReader(stream, enc);
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                WriteLog(e);
            }
            finally
            {
                if (reader != null)
                {
                    //reader.Close();
                    reader.Dispose();
                }
                //if (stream != null)
                //{
                //    //stream.Close();
                //    stream.Dispose();
                //}
            }
            return result;
        }
        /// <summary>
        /// 读取Appliction目录下的文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="enc"></param>
        /// <returns></returns>
        public static string AppReadTxt(string filePath, Encoding enc)
        {

            string appPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = appPath + filePath;
            return ReadTxt(path, enc);
        }
        /// <summary>
        /// 读取Appliction目录下的文件(UTF-8)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string AppReadTxt(string filePath)
        {
            return AppReadTxt(filePath, System.Text.Encoding.UTF8);
        }
    }
}
时间: 2024-11-06 22:33:23

IOHelper(自制常用的输入输出的帮助类)的相关文章

Java常用的输入输出方法

对于经常上机刷题的来说,首先得解决输入输出方法,Java的输入输出流在Java学习过程的后面部分才会接触,但是我们可以掌握一些简单的,常用的输入输出方法 首先输出 大家最熟悉的莫过于输出方法,直接用System.out.println()或者System.out.print()了下面一个实例 public class Main{ public static void main(String[] args){ System.out.println("hello_1!"); System.

C#-I/O输入输出之FileStream类

I/O数据流提供一种向后备存储读取字节的方式,它是在.NET Framework中执行读写文件操作时的一种非常重要的介质. 我们可以将流视为一组连续的一维数据,包含开头和结尾,并且其中的游标指示了流中的当前位置. 1.流操作 流中包含的数据可能来自内存.文件或TCP/IP套接字,基本操作: (1)读取:将数据从流传输到数据结构(如字符串货字节数组)中 (2)写入:将数据从数据源传输到流中 (3)查找:查询和修改在流中的位置 2.流类型 流由Stream类表示,该类构成了所有其他流的抽象类.不恩给

C++学习43 输入输出有关的类和对象

输入和输出是数据传送的过程,数据如流水一样从一处流向另一处.C++形象地将此过程称为流(Stream).C++的输入输出流是指由若干字节组成的宇节序列,这些宇节中的数据按顺序从一个对象传送到另一对象.流表示了信息从源到目的端的流动.在输入操作时,字节流从输入设备(如键盘.磁盘)流向内存,在输出操作时,字节流从内存流向输出设备(如屏幕.打印机.磁盘等).流中的内容可以是ASCII字符.二进制形式的数据.图形图像.数字音频视频或其他形式的信息. 实际上,在内存中为每一个数据流开辟一个内存缓冲区,用来

C#常用的集合类型(ArrayList类、Stack类、Queue类、Hashtable类、SortedList类)

1.ArrayList类 ArrayList类主要用于对一个数组中的元素进行各种处理.在ArrayList中主要使用Add.Remove.RemoveAt.Insert四个方法对栈进行操作.Add方法用于将对象添加到 ArrayList 的结尾处:Remove方法用于从 ArrayList 中移除特定对象的第一个匹配项:RemoveAt方法用于移除 ArrayList 的指定索引处的元素:Insert方法用于将元素插入 ArrayList 的指定索引处. 示例 ArrayList的使用 示例将介

游戏中常用到的碰撞检测帮助类

游戏中咱们经常用到碰撞检测,一般的游戏引擎也会自带有自身的检测碰撞类,但有时候不过灵活,这时候我们希望自己可以自定义一些碰撞检测类.tong顶一些啊... import android.graphics.Rect; public class CollisionUtil { /** * 矩形碰撞检测 参数为x,y,width,height * * @param x1 *            第一个矩形的x * @param y1 *            第一个矩形的y * @param w1

常用cookie处理方法工具类

功能:cookie的添加.删除.获取值 1 import java.io.UnsupportedEncodingException; 2 import java.net.URLDecoder; 3 4 import javax.servlet.http.Cookie; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 /** 9 * 常用cook

java 常用的验证方法帮助类

import java.text.ParseException; import java.util.Collection; import java.util.Map; /** * 常用的验证方法帮助类,提供对字符串,集合,数组,数值的验证 * * */ public class ValidateHelper { /** * 判断一个字符串是否不是一个空字符串 * * @param s 要判断的字符串 * @return 如果不为空返回true,否则返回false */ public static

自制常用工具类

using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Drawing.Imaging; usi

最最常用的 100 个 Java 类(转)

大部分的 Java 软件开发都会使用到各种不同的库.近日我们从一万个开源的 Java 项目中进行分析,从中提取出最常用的 Java 类,这些类有来自于 Java 的标准库,也有第三方库.每个类在同一个项目中只计数一次,下面的列表中显示前 100 名的类. 以下列表中按使用最多的类进行排序,第三个数值表示 10000 个项目里使用到该类的项目数,而完整的列表请看 here. java.util.ArrayList(6958) java.io.IOException(6866) java.util.