私が尋ねている質問を明確にさせてください。私が取り組んでいるJavaプログラムは、JLine2というreadlineライブラリを介してキーボードから入力を受け取ります。ライブラリは、スペースで区切られたコマンドと引数に分割するのではなく、行タイプ全体をコマンドとして受け取ります。私が探しているのは、入力として渡される文字列を分割する安全な方法です。
配列を使用してみましたが、概念の初期段階にあるため、最大のコマンドがいくつの引数を持つかまだわからないため、事前に初期化された配列を使用するとうまくいかないと思います。私が遭遇した問題は、配列内の null 値をチェックするとき、または特定のコマンドまたは引数が存在するかどうかをチェックするときです。Java は、配列インデックスが範囲外か何かについて例外をスローし続けます。配列には実際には、配列インデックス 0 のコマンドの引数である配列インデックス 1 の値がないためです。
だから私が探しているのは、配列例外が発生したときにJavaが私に怒鳴ることなく、文字列を取得して安全に部分に分割する方法です。
これが私が提供できる非常にスリムなコードです...
ConfigShell.class
package shell;
import java.io.IOException;
import configFS.ConfigFS;
import jline.console.ConsoleReader;
public class ConfigShell {
private ConfigFS config;
public ConfigShell() throws IOException {
config = new ConfigFS();
}
public void init() throws IOException {
ConsoleReader console = new ConsoleReader();
// When the program starts we want to be placed at / (root).
console.setPrompt(">> ");
// In this case an infinite loop is better than a loop based on whether line is equal to null.
// This allows line to be equal to null and still stay inside the shell.
while (true) {
String line = console.readLine();
if (line != null) {
// If pre-initialize the array I can check for null as a value for an array index.
// If I did this at time I needed the array and there were not enough index occupied the system would return an exception.
String[] cmdArgs = new String[4];
// We need to split up the incoming line because JLine2 does not do it for me.
// This allows me to evaluate the entire command piece by piece rather all at once.
cmdArgs = line.split("\\s+");
if (cmdArgs[0] != null && cmdArgs[0].equals("add")) {
if (cmdArgs[1] != null && cmdArgs[1].equals("server")) {
if (cmdArgs[2] != null) {
config.addServer(cmdArgs[2]);
System.out.println("Added server " + cmdArgs[2] + " to the configuration successfully.");
}
}
}
if (cmdArgs[0].equals("exit")) {
System.exit(0);
}
}
}
}
}
テストに関する注意: 私の Start.class メイン メソッドは、上記のファイルの init メソッドを呼び出します。