简体   繁体   中英

how to compile & run java program in another java program-netbeans

I tried running the accepted answer in question using netbeans. The class file created but it is not executing. Here is my code

import java.io.*;

public class Laj {

  private static void printLines(String name, InputStream ins) throws Exception {
    String line = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(ins));
    while ((line = in.readLine()) != null) {
      System.out.println(name + " " + line);
    }
  }

  private static void runProcess(String command) throws Exception {
    Process pro = Runtime.getRuntime().exec(command);
    printLines(command + " stdout:", pro.getInputStream());
    printLines(command + " stderr:", pro.getErrorStream());
    pro.waitFor();
    System.out.println(command + " exitValue() " + pro.exitValue());
  }

  public static void main(String[] args) {
    try {
      runProcess("javac /home/shibin/NetBeansProjects/JavaApplication3/src/javaapplication3/Main.java");
      Thread.sleep(1000);
      runProcess("java /home/shibin/NetBeansProjects/JavaApplication3/src/javaapplication3/Main");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Main.java is just a print statement,

  public class Main {
  public static void main(String[] args) {
System.out.println("Done");
 }
 }

and i am getting error

javac /home/shibin/NetBeansProjects/JavaApplication3/src/javaapplication3/Main.java exitValue() 0

java /home/shibin/NetBeansProjects/JavaApplication3/src/javaapplication3/Main stderr: Error: Could not find or load main class 
.home.shibin.NetBeansProjects.JavaApplication3.src.javaapplication3.Main

java /home/shibin/NetBeansProjects/JavaApplication3/src/javaapplication3/Main exitValue() 1

The command for running java program is java packageName.programName or java packageName/programName The problem here is that you are running the code with java pathOfProgram/programname . To resolve this you have to supply classpath using -cp argument followed by the programPath like shown below:

java -cp pathOfProgram packageName.programName

尝试这个:

runProcess("java -cp /home/shibin/NetBeansProjects/JavaApplication3/src/javaapplication3 Main");

Your java command should have classpath argument. Prefer to use cmd array. Java process api is not xommand line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM