Anil
Anil

Reputation: 2455

How to call another java program using eclipse

The following code(when executed) prompts the user to enter any java class name to execute.

import java.io.*;
public class exec {

public static void main(String argv[]) {
    try {
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);

        System.out.println("Enter the java class name");
        String s=br.readLine();

        Process pro=Runtime.getRuntime().exec(s);

        BufferedReader in=new BufferedReader(new InputStreamReader(pro.getInputStream()));
        String line=null;
        while((line=in.readLine())!=null) {
            System.out.println(line);
        }
        in.close();
    } catch(Exception err) {
        err.printStackTrace();
    }
}

This code works fine if I'm using command prompt and I'm able to execute another java program. But I'm unable to do the same using eclipse.No output or error is showing up once I enter the java class name.

I'm new to eclipse. Need help.

Upvotes: 1

Views: 1738

Answers (2)

Bohemian
Bohemian

Reputation: 425043

You can't "execute" a java class, so your code as posted can't work.

Instead, you'll need to execute "java" and pass to it the classpath and class name as parameters, something like this:

String s = br.readLine();

String[] cmd = {"java", "-cp", "/some/path/to/your/jar/file", s};

Process pro = Runtime.getRuntime().exec(cmd);

Upvotes: 3

Gabriel
Gabriel

Reputation: 3045

Do you just enter the name of the class, or do you also enter the directory of where the program is located? I think it doesn't work in eclipse because you need to specify where the file is... like C:\Users\Me\workspace\ProjectName\src\filename

Upvotes: 0

Related Questions