Reading a substring from a string value

2019-08-15 19:20发布

问题:

I wrote a Java command line application for Windows, and stored the result of that cmd in a string variable.

My question is: Is it possible to get a substring from that variable from where I had stored the output of the cmd?

I want to put a statement that creates an action if a substring is found in the cmd output string variable.

Here are the methods of the application class:

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();
 }

回答1:

A quick example of how to use contains() as in your example:

String r = reader.nextLine();

System.out.println(r);

if (r.contains("abc")) {
    System.out.println("abc found");
} else {
    System.out.println("abc not found");
}

This will print abc found if "abc" is a substring within r.



回答2:

Consider java.util.regex.Pattern it is a more flexible way to test whether a string contains what you expect



标签: java cmd