0

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

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

3 Comments

I did use your example, but still I can not get out.txt file with result;(
Where do you search output file out.txt?
I run programm, and file is created. In directory, where from I start class Main
2

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

3 Comments

What exactly you by full path? I was thinking that I supplied a full path in both cases for javac and java. I'm newer and if i did understand you in wrong way -sorry
Full path to the javac ie C:\Progam Files\Java\JDK\bin\javac, or use llya example ;)
The thing is that javac works ok and creates test.class file. The problem is java. But I did wrote the full path to javac. Still can not get test.class runned

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.