Search code examples
cassandracqlnodetool

How can i run and return the cassandra nodetool command and its output


How can i run and return the cassandra nodetool command and its output using Java. I checked this SO question but there is no clarity about how to do it exactly.


Solution

  • import java.io.InputStreamReader;
    
    public class ShellTest {
         public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
                // Get runtime
                java.lang.Runtime rt = java.lang.Runtime.getRuntime();
                // Start a new process: UNIX command ls
                java.lang.Process p = rt.exec("ccm node1 nodetool status");
                // You can or maybe should wait for the process to complete
                p.waitFor();
                System.out.println("Process exited with code = " + p.exitValue());
                // Get process' output: its InputStream
                java.io.InputStream is = p.getInputStream();
                java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(is));
                // And print each line
                String s = null;
                while ((s = reader.readLine()) != null) {
                    System.out.println(s);
                }
                is.close();
            }
    }