正文

streamreader和streamwriter 例子2007-09-18 10:39:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/jixian/29488.html

分享到:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace _5_4
{
    class Program
    {
        private const string path = "E:\\test2.txt";
        static void Main(string[] args)
        {
            StreamWriter sw = null;
            try
            {
                sw = createfile();
                writetext(sw);
                readtext(sw);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
        }

        private static StreamWriter createfile()
        {
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            return new StreamWriter(fs);
        }
        private static void writetext(StreamWriter sw)
        {
            sw.WriteLine("testing the streamwriter capabilities");
            sw.WriteLine("writing bboolean {0}",true);
            sw.WriteLine("writing float {0}",6.78);
            sw.WriteLine("writing long {0}",4576457L);
            sw.Write(445);
            sw.WriteLine(new person("jack"));
            sw.Flush();
        }
        private static void readtext(StreamWriter sw)         //读取流中数据
        {
            StreamReader sr = new StreamReader(sw.BaseStream); //返回基础流,也不知道是什么意思??????懂得的说下啊
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            while (sr.Peek() > -1)  //检测 下一个字符是否可用,但指针并不向后移动。如到末尾,则返回-1
            {
                Console.WriteLine(sr.ReadLine()); //读取一行后,指针向后移动,
            }
        }
    }
    class person
    {
        string name;
        public person(string name) { this.name = name; }
    }
}

阅读(2158) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册