Hello World
Hello World

Reputation: 395

How Do I Compile And Run A .java File In Java?

I tried this but it didin't work. My method to launch command prompt commands:

public static void executeCommand(String command, String path){
  File folder = new File(path);
  ProcessBuilder pb = new ProcessBuilder(command);
  pb.directory(folder.getAbsoluteFile()); 
  pb.redirectErrorStream(true);
  try{
    pb.start();
  }catch (IOException e){
    e.printStackTrace();
  }
}  

`

and the code to call the methods:

executeCommand("javac "+str+".java", path);
executeCommand("java "+str, path);

But it's throwing an IOException. I was wondering if this was the wrong way to do it and how I can fix it. "str" is the .java file. The path is the path of the folder to run it in.

Upvotes: 1

Views: 286

Answers (3)

Neeraj Jain
Neeraj Jain

Reputation: 7720

You are getting IOException

java.io.IOException: Cannot run program "javac ":

You need to separate the arguments into separate strings like this :

executeCommand(new String[]{"javac",str+".java"},path);
                              /\   
                              ||
                   Please notice No Space like this "javac "
                                                          ^^
                                                       Remove(Space)

Also Change the Argument List in your executeCommand method like this :

public static void executeCommand(String [] command, String path)

I have just tried and Program executed successfully after removing space from "javac" .


Alternatice way to Execute command

You Can use Runtime#exec() method

public static void executeCommand(String command){
   try{
        Process process = Runtime.getRuntime().exec(command);
        InputStream error = process.getErrorStream();
        InputStreamReader isrerror = new InputStreamReader(error);
        BufferedReader br = new BufferedReader(isrerror);
        String line=null;
        while ((line = bre.readLine()) != null) {
          System.out.println(line);
        }
        process.waitFor();
      }catch (Exception e){
       e.printStackTrace();
     }
}

Call them

executeCommand("javac "+str+".java");
executeCommand("java "+str);

I have used the ErrorStream to check wheather there is a compile time Error in .java file i am compiling

Upvotes: 0

Makoto
Makoto

Reputation: 106498

There's actually a standard way to do this in Java - using the JavaCompiler class. You require that tools.jar is available on your classpath, though.

The documentation on that page should just about get you started, but for completeness, here is an example.

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, Locale.US, Charset.defaultCharset());
File[] files = new File[]{new File("/path/to/java/source/file/you/want/to/compile")};
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

Iterable<? extends JavaFileObject> compilationUnits1 =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files));
Boolean call = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits1).call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
    System.out.println(diagnostic);

}

System.out.println("compiled successfully: " + call);

If you're going to compile the contents of an entire directory, then you would want to change your array slightly:

File directory = new File("/path/to/directory");
File[] files = directory.listFiles();

Upvotes: 1

abcdef
abcdef

Reputation: 441

You need to say where javac and Java are, the directory you pass in is the directory of the file not the directory of the binary of the process you want to run. Either qualify javac / java fully or set the directory to be where the executable is

Upvotes: 0

Related Questions