Get the result of the method and save it to a variable

839 views Asked by At

There is such code, I pass two parameters to the input and get the result of this method in the console, I need to save the result in a variable and pass it to another method how to do it right? Please do not rush tomatoes with a beginner in programming, I will be glad to any help. The result of the screen method.

enter image description here

  public static String activation(String serialNumber, String keyName) throws IOException, InterruptedException, SQLException {
    LocalDate futureDate = LocalDate.now().plusMonths(12);
    String formattedDate = futureDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    String[] command =
            {
                    "cmd",
            };
    Process p = Runtime.getRuntime().exec(command);
    //new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
    new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
    PrintWriter stdin = new PrintWriter(p.getOutputStream());
    stdin.println("C:\\tdes_ecb.exe " + serialNumber + " " + keyName + " " + formattedDate);

    stdin.close();

    int returnCode = p.waitFor();
    String code = Integer.toString(returnCode);

    return code;
}

static class SyncPipe implements Runnable {
    public SyncPipe(InputStream istrm, OutputStream ostrm) {
        inputStream = istrm;
        outputStream = ostrm;

    }

    public void run() {
        try {


            final byte[] buffer = new byte[1024];
            for (int length = 0; (length = inputStream.read(buffer)) != -1; ) {
                outputStream.write(buffer, 0, length);


                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < buffer.length; i++) {
                    char c = (char) buffer[i];
                    sb.append(c);
                }
                String convertedString = sb.toString();

                key(convertedString);


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final OutputStream outputStream;
    private final InputStream inputStream;
}

public void SyncPipe(InputStream inputStream, OutputStream outputStream) {
    this.inputStream = inputStream;
    this.outputStream = outputStream;
}
2

There are 2 answers

1
res On BEST ANSWER

For you to get the result of Runtime.getRuntime().exec(command) into a variable, there is no need for a separate thread, you can simple read it right from your object Process and store in a String or StringBuilder, after this it is a matter of understanding the text and splitting it based on your rules.

To immediately read the result of a process:

final StringBuilder ret = new StringBuilder();

final Runtime rt = Runtime.getRuntime();
final String[] commands = { "cmd", "/c", "cd c:\\myuser" };

final Process proc = rt.exec(commands);

final BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
final BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

String s = null;

while ((s = stdInput.readLine()) != null) {
    ret.append(s).append("\n");
}

while ((s = stdError.readLine()) != null) {
    ret.append(s).append("<br />");
}
String res = ret.toString();

After the code above you‘ll have all the text from the results in a String, now it is a matter of splitting it and/or removing unnecessary information. For this you can use the methods indexOf, split and removeAll combined, they are all methods inside the String class.

In you case, to make it simple we can divide the splitting in 3 stages. 1) Ignore the first empty line (\r\n) 2) Ignore the whole first line (command and arguments) 3) Use only the text starting from the position 0 until the next line break

String res = "\r\nC:\\User\\aaa\\bbb\\ccc\\tdex_ecb.exe 000000 111111 33333 44444 \r\n INFO I WANT\r\n C:\\\\User\\\\aaa\\\\bbb\\\\ccc\\\\";

res = res.substring(2);
res = res.substring(res.indexOf("\r\n")+2);
res = res.substring(0, res.indexOf("\r\n"));

System.out.println(res);

Now your variable res has only the text you want to pass to another method.

1
Sree Kumar On

I am not clear of some parts of your requirement. If it is to get the output of the child process as input in the main Java process, then I don't think it is feasible directly through the Java APIs.

Indirect way of getting child process output in the main Java process

I am not sure if you tried this, but you can redirect the output of the child process into a file and read from that file once the process is over, within the same process. (Of course, if your output data in sensitive, you may not want to do this.)

String filePath = "C:/Temp/abc.txt";

/* Create the process and redirect its output to a new file. */
ProcessBuilder pb = new ProcessBuilder().command( "C:\\Temp\\echo.bat" ) //Replace this with your command
     .redirectOutput( Redirect.to( new File( filePath ) ) );
Process p = pb.start();
p.waitFor(); //Now, wait for the process to get over...

/* Now, read from the generated file. */
List<String> lines = Files.readAllLines( Paths.get( filePath ) );

Linking the outputs and inputs, resp., of child and main process

However, if your need is to simply display the output of the child process in the console of the main Java process, you may do this.

Process p = new ProcessBuilder().command( "C:\\Temp\\echo.bat" ) //Replace this with your command
        .inheritIO().start();
p.waitFor();