2012-12-16 77 views
1

我为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(); 
} 
+0

您可以使用String类'包含()'方法来搜索其他内部字符串串。 –

+0

通常您想要关键词后您想要的文字,例如一次ping所需的时间。我建议使用'indexOf',以便知道文本的位置。 –

回答

1

如何使用在您的例子一个简单的例子:

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 found如果​​是内子r

+0

非常感谢,现在工作正常。 – sofian

0

考虑java.util.regex.Pattern中它是检验一个更灵活的方式一个字符串是否包含你所期望的