zoukankan      html  css  js  c++  java
  • 文件读取、写入

       

    文件的读操作

       static void Main(string[] args)
            {
                string path = "";
                Console.WriteLine("请输入要读取的文件的文件名,包括路径");
                path = Console.ReadLine();
                if (!File.Exists(path))
                {
                    Console.WriteLine("文件不存在");
                    return;
                }

                try
                {
                    FileStream file = new FileStream(path, FileMode.Open);
                    byte[] bt = new byte[file.Length];
                    file.Read(bt, 0, bt.Length);
                    string str = Encoding.Default.GetString(bt);
                    Console.WriteLine(str);
                    Console.ReadLine();
                }
                catch (System.Exception e)
                {
                    Console.WriteLine("读取文件出错");
                }

            }

    文件的写操作:

           static void Main(string[] args)
            {
                //FileStream fs1 = File.Create("test1");
                //fs1.Close();
                //Console.ReadLine();

                string path = "";
                string content = "";
                Console.WriteLine("请输入要保存的文件的文件名,包括路径");
                path = Console.ReadLine();
                Console.WriteLine("请输入要保存的内容 ");
                content = Console.ReadLine();
                try
                {
                    FileStream file = new FileStream(path, FileMode.Create);
                    byte[] bt = Encoding.UTF8.GetBytes(content);
                    file.Write(bt, 0, bt.Length);
                    file.Flush();
                }
                catch (System.Exception e)
                {
                    Console.WriteLine("创建或写入文件时出错");
                 
                }

     // 读取文件流

         static void Main(string[] args)
            {
                Console.WriteLine("请输入要读取文件的文件名,包括路径");
                string path = Console.ReadLine();
                if (!File.Exists(path))
                {
                    Console.WriteLine("文件不存在");
                    return;
                }

                FileStream readStream = new FileStream(path, FileMode.Open);
                BufferedStream readBuffered = new BufferedStream(readStream);
                byte[] bt = new byte[readBuffered.Length];
                readBuffered.Read(bt, 0, (int)readBuffered.Length);
                Console.WriteLine(Encoding.Default.GetString(bt));
                readBuffered.Close();
                Console.ReadLine();
            }

  • 相关阅读:
    520了,用32做个简单的小程序
    安装 部署 postgresql数据库 搭建主从节点 (业务库)
    年轻就该多尝试,教你20小时Get一项新技能
    谷歌搜索进阶(二)
    谷歌搜索进阶(一)
    Linux进程前后台管理(&,fg, bg)
    VTF/AMROC安装指南
    神经网络学习笔记(三):三种典型的架构
    神经网络学习笔记(二):feedforward和feedback
    神经网络学习笔记(一)
  • 原文地址:https://www.cnblogs.com/tianjinquan/p/1858425.html
Copyright © 2011-2022 走看看