ですからJavaでコンソールアプリってのはどうしても多少の困難を覚悟せねばなりません。コマンドライン処理など想定されていないわけです。
プロパティファイルで初期化パラメタを設定なる方法がありますが、昔ながらの伝統的スタイルを継承し、クラシックなノリでコマンドライン引数なるものを使うとプロパティなどというものを使わずまるでUnix/Linux/Gnuのコマンドのようなプログラムが書けます。
ここは外部ライブラリを使うのがオススメです。Apache Commons CLI を使う方法を示します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String args[]) { | |
Options opt = new Options(); | |
try { | |
opt.addOption("?", OPTION_HELP, false, "print this message"); | |
Option option = Option.builder("f").required(true).longOpt(OPTION_FILE).hasArgs().desc("file name").build(); | |
opt.addOption(option); | |
Option dirOption = Option.builder("d").required(true).longOpt(OPTION_DIR).hasArgs().desc("target directory") | |
.build(); | |
opt.addOption(dirOption); | |
CommandLineParser parser = new DefaultParser(); | |
CommandLine cmd = parser.parse(opt, args); | |
if (cmd.hasOption(OPTION_HELP)) { | |
throw new Exception(); | |
} else if (cmd.hasOption(OPTION_DIR) && cmd.hasOption(OPTION_FILE)) { | |
String dir = cmd.getOptionValue(OPTION_DIR); | |
String fileName = cmd.getOptionValue(OPTION_FILE); | |
new FindFile(fileName, dir); | |
}else{ | |
throw new Exception(); | |
} | |
} catch (Exception e) { | |
HelpFormatter help = new HelpFormatter(); | |
help.printHelp("DirList", opt, true); | |
} | |
} |