zoukankan      html  css  js  c++  java
  • C#读txt文件并写入二维数组中(txt数据行,列未知)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace 二维数组
    {
        class Program
        {
            static void Main(string[] args)
            {
                int row = 0;//
                int col = 0;//lie
                FileStream fs;
                string path = @"C:Documents and SettingsAdministrator桌面1.txt";
                fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader sr;
                sr = new StreamReader(fs);
                List<double[]> arrary = new List<double[]>();  
    
                while (!sr.EndOfStream)
                {
                    string[] arr = sr.ReadLine().Split(' ');
                    col = arr.Length;
                    double[] temp=new double[col];
                    for (int x = 0; x < col; x++)
                    {
                        temp[x] = Convert.ToDouble(arr[x]);
                    }
                    arrary.Add(temp);
                    for (int y = 0; y < col; y++)
                    {
                        Console.Write(arrary[row][y] + " ");
                    }
                    row++;
                    Console.WriteLine("
    ");
                }
                sr.Close();
                fs.Close();
                Console.Read();
            }
        }
    }

    arrary定义的泛型 double数组类型。是二维数组的使用方法。可以通过arrary[x][y],进行数据的读取 .注意必须先add 每次add一次 ,x就加1.

    如果arrary这样定义 

     List<double[,]> arrary = new List<double[,]>();   那么读取数据应该这样arrary[num][x,y] 每次add一次 num都会+1, add赋值时也必须是[,]的对象。

    注意:.net中有一些非托管对象有close和dispose两个方法,最安全的做法是先close 再 dispose。

    后来啊 一看还有好多更简单的做法了 你瞧:

      public short[] readFile(string fileName)
            {
                string[] dt = File.ReadAllLines(fileName);
                short[] b = new short[dt.Length];
                for (int i = 0; i < b.Length; i++)
                {
                    b[i] = short.Parse(dt[i]);
                }
                return b;
            }

    这就好了 ,简单方便 多好

     
  • 相关阅读:
    简单理解jQuery中$.getJSON、$.get、$.post、$.ajax用法
    适配器模式(Adapter Pattern)
    什么样的登录框才算是优秀的?
    transient的作用及序列化
    MySQL索引实现原理
    concurrentHashMap原理分析和总结(JDK1.8)
    HashMap实现原理(JDK1.8)
    深入理解Java中的IO
    多线程系列
    多线程系列
  • 原文地址:https://www.cnblogs.com/zhayunjia/p/4040151.html
Copyright © 2011-2022 走看看