2

I`m new at Java and I need to run CMD or Powershell in java because i want to find out the current RAM utilization and the current disk distribution On StackOverflow are many similar questions but I don't get it.

Here is my code, I got it from here:

package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
    }

    public static class CmdTest {
        public static void main(String[] args) throws Exception {
            ProcessBuilder builder = new ProcessBuilder(
                    "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while (true) {
                line = r.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
        }
    }

}

I only get an empty console and I don't know why.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Lukas Wenzel
  • 45
  • 1
  • 7

1 Answers1

6

Here:

public static void main(String[] args) {
}

The main method of your Main class is empty, does nothing.

You then added another inner class of Main, named CmdTest. But that class, respectively its main gets never called.

My suggestion, simply go, remove the CmdTest class, and put its code into your existing Main.main():

public class Main {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder(...

You could also rename Main.java to CmdTest.java, and (basically) remove the old Main, and have your CmdTest be its own public top level class.

And just for the record: formatting matters big time. It took me 2 minutes to figure your problem. Why? Because of misleading formatting. If you had indented reasonably, the underlying problem would have been obvious in 5 seconds. Thus: always indent consistently, and put } on a new line, even when the block/method is empty!

Finally: given the self-answer by the OP with more syntax experiments, the real answer here: step back. Look at this for example to understand how a correct class + main have to look like. Understand the details, then start inserting your own code.

GhostCat
  • 137,827
  • 25
  • 176
  • 248