让我澄清一下我要问的问题。我正在开发一个 java 程序,它通过一个名为 JLine2 的 readline 库从键盘获取输入。该库将整个线型作为命令,而不是将其分解为空格分隔的命令和参数。我正在寻找一种安全的方法来分解作为输入传递的字符串。
我尝试过使用数组,但由于我处于概念的早期阶段,我还不知道我最大的命令将有多少个参数,因此使用预初始化的数组我认为行不通。我遇到的问题是当我检查数组中的空值或检查是否存在特定命令或参数时。 Java 不断抛出关于数组索引超出范围之类的异常。因为数组实际上没有数组索引 1 的值,而数组索引 1 是数组索引 0 中命令的参数。
所以我正在寻找一种方法来获取字符串并将其安全地分割成多个部分,而不会在发生数组异常时让 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 main 方法调用上述文件中的 init 方法。
最佳答案
你可以这样做:
String cmdArgs = line.split("\\s+");
然后,在访问任何特定索引之前,检查数组的大小,以免出现 ArrayIndexOutOfBoundException
类似这样的事情:
if(cmdArgs.length>=2){
//It means you have at least 2 elements
//Now its safe to access cmdArgs[0] and cmdArgs[1]
}
关于java - 在 Java 中将字符串分成多个部分的安全方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15778587/