我为 Windows 编写了一个 Java 命令行应用程序,并将该 cmd 的结果存储在字符串变量中。
我的问题是:是否可以从我存储 cmd 输出的变量中获取子字符串?
我想放置一个语句,如果在 cmd 输出字符串变量中找到子字符串,该语句将创建一个操作。
以下是应用程序类的方法:
public static void main(String[] args) throws IOException, InterruptedException
{
runWndCommand("ping 192.168.11.3");
}
public static void runWndCommand(String cmd) throws IOException, InterruptedException
{
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(new String[] { "cmd.exe", "/C", cmd });
Scanner reader = new Scanner(p.getInputStream());
while (reader.hasNext())
{
String r=reader.nextLine();
System.out.println(r);
}
p.waitFor();
}
最佳答案
如何使用 contains()
的快速示例,如您的示例所示:
String r = reader.nextLine();
System.out.println(r);
if (r.contains("abc")) {
System.out.println("abc found");
} else {
System.out.println("abc not found");
}
如果“abc”
是r
中的子字符串,这将打印abc找到
。
关于java - 从字符串值中读取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904318/