如何从另一个java程序启动java程序?

时间:2013-03-07 10:10:26

标签: java netbeans

我在netbeans项目的包中有2个java程序。 1是Run.java,另一个是JdbcSqlServerConnectivity.java。我之前提到了关于这个主题的问题,但没有一个解决方案似乎有效。我得到以下错误

javac JdbcSqlServerConnectivity.java stderr: javac: file not found: JdbcSqlServerConnectivity.java
javac JdbcSqlServerConnectivity.java stderr: Usage: javac <options> <source files>
javac JdbcSqlServerConnectivity.java stderr: use -help for a list of possible options
javac JdbcSqlServerConnectivity.java exitValue() 2
java JdbcSqlServerConnectivity stderr: Error: Could not find or load main class JdbcSqlServerConnectivity
java JdbcSqlServerConnectivity exitValue() 1

Run.java代码

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

public class Run {

  private static void printLines(String name, InputStream ins) throws Exception {
    String line;
    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 JdbcSqlServerConnectivity.java");
      runProcess("java JdbcSqlServerConnectivity");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

提前致谢

2 个答案:

答案 0 :(得分:0)

您应该提供文件JdbcSqlServerConnectivity.java的完整系统路径。例如,如果JdbcSqlServerConnectivity.java位于D:\Temp\com\example目录中,那么您应该指定如下:

runProcess("javac D:\\Temp\\com\\example\\JdbcSqlServerConnectivity.java");
runProcess("java D:\\Temp\\com\\example\\JdbcSqlServerConnectivity");

答案 1 :(得分:0)

试试这个:

runProcess(&#34; java -cp fullpath JdbcSqlServerConnectivity.java&#34;);