どっとねっとふぁん

C# Tips And Samples
in 検索

21.固定長ファイル読み取りクラス

最新の投稿は、投稿日時: 06-22-2005, 4:21 午後 投稿者: ono です。スレッドには 0 件の返答があります。
投稿のソート: 前へ 次へ
  •  06-22-2005, 4:21 午後 30

    21.固定長ファイル読み取りクラス

    固定長のデータを扱うためのクラスを作成してみました。

    -------------------------------------------------------
    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Specialized;
    
    public class FixedLenRecReader
    {
        int pos = 0;
        int length = 0;
        StringCollection sc = new StringCollection();
        Encoding sjis = Encoding.GetEncoding("Shift-JIS");
        byte [] b = null;
    
        public int    Length         { get { return length; } }
        public string CurrentData    { get { return sc[pos-1]; } }
    
        public FixedLenRecReader(string fn)
        {
            string str = null;
            if(!File.Exists(fn))
                throw new ArgumentException("指定されたファイルが存在しません");
    
            StreamReader sR = new StreamReader(fn, sjis);
            while((str=sR.ReadLine())!=null)
            {
                if(str!="")
                {
                    sc.Add(str);
                    length++;
                }
            }
            sR.Close();
        }
    
        public bool MoveNext()
        {
            if(length==pos++)
                return false;
            b = sjis.GetBytes(CurrentData);
            return true;
        }
    
        public string GetData(int start, int length)
        {
            byte [] bdata = new byte[length];
            for(int i = start-1, j = 0; j < length; i++, j++)
                bdata[j] = bIdea [I];
            return sjis.GetString(bdata);
        }
    }
    
    -------------------------------------------------------

    テストデータとして以下のデータを用います。

    -------------------------------------------------------
    00001小野 修司     オノ シュウジ   119651231
    00002鈴木 一郎     スズキ イチロウ  119780306
    00003佐藤 花子     サトウ ハナコ   219850601
    
    -------------------------------------------------------

    次のようなプログラムで固定長のデータを扱うことができます。

    -------------------------------------------------------
    using System;
    
    public class Sample
    {
        public static void Main(string[] args)
        {
            FixedLenRecReader record = new FixedLenRecReader("Test.txt");
            while(record.MoveNext())
            {
                Console.WriteLine(record.CurrentData);
                Console.WriteLine("ID:{0}", record.GetData(1, 5));
                Console.WriteLine("氏名:{0}", record.GetData(6, 20));
                Console.WriteLine("カナ:{0}", record.GetData(26, 20));
                Console.WriteLine("性別:{0}", record.GetData(46, 1));
                Console.WriteLine("生年月日:{0}", record.GetData(47, 8));
            }
        }
    }
    
    -------------------------------------------------------


    あおい情報システム株式会社
     小野修司(どっとねっとふぁん)
RSS ニュースフィードで参照
SkinName:iroha_CS2
Powered by Community Server, by Telligent Systems