Question

I'm trying to run a Java program from another Java application. Here is my code:

public class Main {
  public static int Exec() throws IOException {
    Process p = Runtime.getRuntime().exec("javac -d C:/Users/Dinara/Desktop/D/bin "
            + "C:/Users/Dinara/Desktop/D/src/test.java");
    Process p1 = Runtime.getRuntime().exec("java -classpath C:/Users/Dinara/Desktop/D/bin test");
    return 0;
  }

  public static void main(String[] args) throws IOException {
    Exec();
  }
}

javac works fine and creates test.class file in bin directory. However java -classpath C:/Users/Dinara/Desktop/D/bin test does not run the test.class file. the content of the test.java:

import java.io.*;
class test {
  public static void main(String args[]) {
    try {  
      FileWriter fstream = new FileWriter("out.txt");
      BufferedWriter out = new BufferedWriter(fstream);
      out.write("Hello Java");
      out.close();
    } catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
    }
  }
}

I suppose that something wrong with recognizing Java command. Could you please give me a sample code for fixing this problem or share idea? I'm using Netbeans to run Main class and the location of the application folder is C:\Users\Dinara\Main

Était-ce utile?

La solution

Use

System.getProperty("java.home") + "/bin/java -classpath C:/Users/Dinara/Desktop/D/bin test" 

instead of

"java -classpath C:/Users/Dinara/Desktop/D/bin test"

Autres conseils

You need to supply the full path to the javac, exec won't use the ath to find it for you

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top