Answers for "How to execute Shell Commands with Java and print the output directly while executing the command"

1

How to execute Shell Commands with Java and print the output directly while executing the command

public static ProcessBuilder buildProcess(String command, File currentDirectory) {
        String runCommand = (System.getProperty("os.name")
                             .toLowerCase()
                             .contains("win")? "cmd /" : "sh -") 
          + "c " + command;
        // split command
        StringTokenizer st = new StringTokenizer(runCommand);
        String[] cmdarray = new String[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++)
            cmdarray[i] = st.nextToken();
       
        return new ProcessBuilder(cmdarray)
                .directory(currentDirectory).inheritIO();
    }
Posted by: Guest on October-27-2021
1

How to execute Shell Commands with Java and print the output directly while executing the command

ProcessBuilder pb = new ProcessBuilder("ping", "localhost");
pb.inheritIO();
try {
    Process p = pb.start();
    int exitStatus = p.waitFor();
    System.out.println(exitStatus);
}
catch (InterruptedException | IOException x) {
    x.printStackTrace();
}
Posted by: Guest on October-27-2021
-1

java get command line output

private static void GetOutput(final Process process) {
    new Thread() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null; 
            try {
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}
Posted by: Guest on June-13-2020

Code answers related to "How to execute Shell Commands with Java and print the output directly while executing the command"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language