ユーティリティの整理

スポンサーリンク

ここまでいくつかユーティリティクラスを作ってきたので一度整理します。パッケージはutilにしてmainメソッドも外しておきます。今後再利用する予定ですので必要があれば見るようにしてください。

入出力のユーティリティ

標準入出力とのやりとりをまとめています。ここでは文字列や数字のユーザー入力や文字列配列からユーザーに選択させるメソッドを記述しています。

標準入力から文字列を取得する
標準入力から文字列を取得するユーティリティを作る
標準入力からint型整数を取得するユーティリティを作る
標準入力からint型整数を範囲指定で取得するユーティリティを作る
標準入力からboolean値を取得するユーティリティを作る
標準入力からオプション選択を取得するユーティリティを作る

package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class TerminalUtil {

  BufferedReader in;
  PrintStream out;

  
  public TerminalUtil() {
    in = new BufferedReader(new InputStreamReader(System.in));
    out = System.out;
  }

  /**
   * 標準入力から文字列を取得する
   * @param message
   * @return 
   */
  public String readString(String message) {
    while(true){
      //メッセージを出力
      out.print(message + ">");
      //入力を取得する
      String str;
      try{
        str = in.readLine();
      }catch(IOException e){
        //例外発生時にはメッセージを出力してやり直す
        out.println(e.getMessage());
        continue;
      }
      //空文字の場合は警告してやり直し
      if(str.isEmpty()){
        out.println("なにも入力がありません。");
        continue;
      }
      //取得した文字を返す
      return str;
    }
  }
  /**
   * 標準入力からオプション選択を取得する
   * @param message
   * @param options
   * @return 
   */
  public String readOption(String message, String[] options){
    //メッセージを出力
    out.println(message);
    for(int i = 0;i < options.length;i++){
      out.println(i + ":" + options[i]);
    }
    int index = readInt("数字を入力してください。", 0, options.length - 1);
    return options[index];
  }
  /**
   * 標準出力からint型整数を取得する
   * @param message
   * @return
   */
  public int readInt(String message) {
    return readInt(message, Integer.MIN_VALUE, Integer.MAX_VALUE);
  }
  /**
   * 標準出力からint型整数を取得する
   * @param message
   * @param min
   * @param max
   * @return
   */
  public int readInt(String message, int min, int max) {
    while(true){
      //メッセージを出力
      out.print(message + ">");
      //入力を取得する
      String str;
      try{
        str = in.readLine();
      }catch(IOException e){
        //例外発生時にはメッセージを出力してやり直す
        out.println(e.getMessage());
        continue;
      }
      int value;
      try{
        //intに変換する
        value = Integer.parseInt(str);
      }catch(NumberFormatException e){
        //変換に失敗した場合は警告してやり直し
        out.println("数字ではありません。");
        continue;
      }
      if(value < min || value > max){
        //値が範囲外の場合は警告してやり直し
        out.println(min + "以上" + max + "以下の数字にしてください。");
        continue;
      }
      //変換した値を返す
      return value;
    }
  }
  /**
   * 標準出力からboolean値を取得する
   * @param message
   * @return 
   */
  public boolean readBoolean(String message) {
    while(true){
      //メッセージを出力
      out.print(message + ": y(es) or n(o)>");
      //入力を取得する
      String str;
      try{
        str = in.readLine();
      }catch(IOException e){
        //例外発生時にはメッセージを出力してやり直す
        out.println(e.getMessage());
        continue;
      }
      //小文字に変換
      str = str.toLowerCase();
      //yかyesの場合はtrueを返す
      if(str.equals("y") || str.equals("yes")){
        return true;
      }
      //nかnoの場合はfalseを返す
      if(str.equals("n") || str.equals("no")){
        return false;
      }
      out.println("入力が正しくありません。");
    }
  }
}

システム情報を利用したユーティリティ

システムやOSやJavaの基本情報を扱うユーティリティです。今のところはOS判別のメソッドのみです。

JavaのプログラムでMacかWindowsかを見分ける

package util;

public class SystemUtil {

  public static boolean isMac() {
    return System.getProperty("os.name").toLowerCase().startsWith("mac");
  }

  public static boolean isWindows() {
    return System.getProperty("os.name").toLowerCase().startsWith("windows");
  }
}

ファイルの入出力ユーティリティ

ファイルの読み込み書き出しをするユーティリティです。

テキストファイルの読み込み
テキストファイルへの書き出し
テキストファイルの読み込みをメソッドにする

package util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;

public class FileUtil {

  /**
   * 指定したパスにファイルを作成しテキストを書き出す
   * @param filePath
   * @param text
   * @throws FileNotFoundException 
   */
  public void printText(String filePath, String[] text) throws FileNotFoundException {
    PrintStream stream = new PrintStream(filePath);
    for (int i = 0; i < text.length; i++) {
      stream.println(text[i]);
    }
    stream.flush();
    stream.close();
  }
  
  /**
   * 指定したファイルからテキストを読み込む
   * @param filePath
   * @return
   * @throws IOException 
   */
  public String[] readText(String filePath) throws IOException {
    ArrayList list = new ArrayList<>();
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    while (reader.ready()) {
      list.add(reader.readLine());
    }
    reader.close();
    return list.toArray(new String[]{});
  }
}
スポンサーリンク

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

%d人のブロガーが「いいね」をつけました。