zoukankan      html  css  js  c++  java
  • c# 读取 txt 文件中数据(int)

    今天在学图的算法做测试是,需要读取文本文件中的点坐标,本来很简单的事情,折腾了半天,记录一下找到的一种简单粗暴的解决方法,以便以后查看。

     第一种方法 : StringReader

    	string line = "";
    using (StreamReader sr = new StreamReader("graph.txt")) // 读取文件所在路径 { while (!sr.EndOfStream) // 判读是否读完 { line = sr.ReadLine(); // 读取一行 string[] points = line.Split(' '); // 拆分当前行 foreach (string item in points) // 转换 string 为 int { int.TryParse(item, out int vertice); Console.Write(vertice + " "); } } }

    第二种方法:BinaryReader (转换为二进制文件读取)

                BinaryWriter bw;
                BinaryReader br;
                string line = "";
                bw = new BinaryWriter(new FileStream("converFromGraph", FileMode.Create));
                using (StreamReader sr = new StreamReader("graph.txt"))
                {
                    while (!sr.EndOfStream)
                    {
                        line = sr.ReadLine();
                        string[] points = line.Split(' ');
                        foreach (string point in points)
                        {
                            int.TryParse(point, out int vertice);
                            bw.Write(vertice);    // 写入二进制文件
                        }
                    }
                }
                bw.Close();
                // 读取二进制文件
                br = new BinaryReader(new FileStream("mydata.dat", FileMode.Open));
                br.BaseStream.Seek(0, SeekOrigin.Begin);
    
                try
                {
                    while (true) // 读完所有文件
                    {
                        int x = br.ReadInt32();
                        Console.WriteLine(x);
                    }
                }
                catch(System.IO.EndOfStreamExceptio)  // 读取文件完成,报异常
                {
                    Console.WriteLine("读写完成");
                }

    数据类型与字节长度:

    byte -> System.Byte   (字节型, 占 1 个字节, 表示 8 位正整数, 范围 0 ~ 255)

    char ->  System.Char  (字符型, 占 2 个字节, 表示一个 unicode 字符)

    short -> System.Int16  (短整型, 占 2 个字节, 表示 16 位整数, 范围 -32,768 ~ 32,767)

    uint ->  System.Uint32 (无符号整型, 占 2 个字节, 表示 16 位正整数, 范围 0 ~ 4,294,967,295)

    int ->    System.Int32    (整型, 占 4 个字节, 表示 32 位整数, 范围 -2,147,483,648 ~ 2,147,483,647)

    short  -> System.Int16 (短整型, 占 2 个字节, 表示  16 位整数,  -32,768 ~ 32,767)

    float -> system.Single (单精度浮点型, 占 4 个字节)

    double -> System.Double (双精度浮点型, 占 8 个字节)

  • 相关阅读:
    sprintf使用
    Android ListView保持选中项高亮
    Creational Patterns创建型模式
    C和指针终于看到指针这一章
    C++随笔001
    TCP reset
    开始看设计模式英文版了
    Excel条件求和
    linux中安装软件,查看、卸载已安装软件方法
    linux vi文本编辑器三种模式切换及常用操作
  • 原文地址:https://www.cnblogs.com/yaolin1228/p/8410377.html
Copyright © 2011-2022 走看看