Aritalab:Lecture/Programming/Java/FileRead

From Metabolomics.JP
Jump to: navigation, search

Contents

タブ区切りテキストを読み込む

ファイルから1行ずつ読み込んで、タブ区切りの2つ目だけを出力、最後に総数を出力するプログラムです。JavaのStringクラスがもつ split(区切り記号) 関数を使って簡単に記述できます。

 public void readFromFile(String filename)
      {
        try
          {
            String line = null;
            int counter =0;
            BufferedReader br = new BufferedReader(
                new FileReader(filename));
            while ((line = br.readLine()) != null)
              {
                String[] data = line.split("\t");
                /* data is an array of tab-separated strings */
                System.out.println( data[1] );
                counter++;
              }
            System.out.println("Read " + counter + " lines.");
          }
        catch (Exception e)
          { e.printStackTrace(); }
      }

コンソールから文字列を読み込む

実行するとプロンプト”>”をコンソールに出力し、キーボードから文字列を受け付けます。 Qを入力すると終了し、それまでに入力した行をベクター(配列)にいれて返します。 Syste.in という入力ストリームを BufferedReader に入れるのがミソです。

import java.util.Vector;
  :
  public Vector<String> readFromKeyboard()
    {
      Vector<String> V = new Vector<String>();
      try { 
        BufferedReader br = new BufferedReader
          (new InputStreamReader(System.in));
        String line =null;
        while (true)
          { /* Loop until input is 'Q' */
            System.out.print(">");
            line = br.readLine();
            /* Exit from the loop */
            if ((line == null) || line.equals("Q"))
              break;
            V.add(line);
          }
      } 
      catch (Exception e)
        { e.printStackTrace(); }
      return V;
    }

ディレクトリにあるファイル名を配列に読み込む

指定されたフォルダ内にある、特定の拡張子がついたファイルだけをすべて集めて、Vectorとして返します。フォルダが入れ子になっている場合は中もすべて見ます。フォルダの階層をすべてたどるのにスタック構造を利用します。

   import java.util.Stack;
   import java.util.Vector;
   :
   static public Vector getFilenames
   (String file, String extension)
      {
        Vector V = new Vector();
        Stack S = new Stack();
        S.push(new File(file));
        try
          {
            while (!S.empty())
              {
                File f = S.pop();
                if (f.isDirectory())
                  {
                    File[] children = f.listFiles();
                    for (int i = 0; i < children.length; i++)
                      S.push(children[i]);
                  }
                else
                  {
                    if (f.getName().endsWith(".mol"))
                      V.add(f);
                  }
              }
          }
        catch (Exception e)
          { System.out.println(e); }
        return V;
      }
Personal tools
Namespaces

Variants
Actions
Navigation
metabolites
Toolbox