1
import java.io.IOException;

public class Test1_Exec {
    public static void main(String[] args) throws IOException {
        Runtime run = Runtime.getRuntime();
        try {
            Process p = run.exec("java Test1");
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test1 {
    public static void main(String[] args)
    {
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("invoked successfully");
    }
}

The problem is that if I run the Test1_Exec in the Eclipse, Test1.txt is not created and no error is reported. But if I type "java Test1" in the command window, Test1.txt is created. Test1_Exec.java and Test1.java are in the same src folder; Test1_Exec.class and Test1.class are in the same bin folder. So what's wrong with the Eclipse? My version of Eclipse is Kepler(20130614-0229).

1
  • It might happens so that java is confused by your JAVA_HOME env variable if it contains whitespaces. Commented Jul 2, 2013 at 11:28

2 Answers 2

3

Put bin folder in your classpath

Process p = run.exec("java -cp path/to/bin Test1");

Currently, java is looking for Test1.class inside your project directory.

Sign up to request clarification or add additional context in comments.

2 Comments

But I think if I add bin folder(including Test1.class) in Eclipse by right clikcing ProjectName->Run As->Run Configuration | classpath Tab --- User Entries --- Advanced --- Add Folders, the statement "Process p = run.exec("java Test1")" would be OK, but it does not work. So why?
@user2158697 Because Eclipse configuration only affects the JVM environment used to run your program. It isn't automatically inherited by the JVM that you instantiate with exec("java ...").
0

Don't you need to give the full path for Test1 in the command? i.e: "java c:\code\Test1" ?

Comments

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.