如何编译&在另一个java program-netbeans中运行java程序

时间:2014-03-17 16:16:34

标签: java netbeans

我尝试使用netbeans在question中运行已接受的答案。已创建类文件但未执行。 这是我的代码

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只是一个打印声明,

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

我收到错误

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

3 个答案:

答案 0 :(得分:0)

运行java程序的命令是java packageName.programNamejava packageName/programName这里的问题是您使用java pathOfProgram/programname运行代码。要解决此问题,您必须使用-cp参数提供classpath,然后使用programPath,如下所示:

java -cp pathOfProgram packageName.programName

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:-1)

您的java命令应该有classpath参数。更喜欢使用cmd数组。 Java进程api不是xommand行。