running command prompt in java program with gui (n

2019-09-16 05:21发布

问题:

hi im trying to do a program that will be able to access command prompt and be able to start solr's start.jar file so my search program could work..the problem is when im using the codes in eclipse, the program runs smoothly but when i transfered my program in netbeans it says that it cannot access the jar file.it doesnt give me any stack trace error that is why i dont know what is wrong..here is my code

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

public class CmdTest {
    public static void main(String[] args) throws Exception {
            ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "/c", "cd \"D:\\Downloads\\solr-4.2.1\\solr-4.2.1\\example\" && java -jar start.jar");
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new      InputStreamReader(p.getInputStream()));
            String line;
            while (true) {
                line = r.readLine();
                if (line == null) { break; }
                System.out.println(line);
            }
        }
          }

the error is just plainly like this : Error:Unable to access jarfile start.jar

回答1:

I can think of a few things to start with...

Each parameter you past to the ProcessBuilder is expected to be a separate argument for the command to be executed. Fine, I'm not 100% if the command you've constructed will work, but it just looks like a mess to me.

Instead, if you want to change the location that the command is executed in, why not just use the directory method of ProcessBuilder, which will change the execution context to the specified location when the command is executed...

public class CmdTest {
    public static void main(String[] args) throws Exception {
            ProcessBuilder builder = new ProcessBuilder("java.exe", "-jar", "start.jar");
            builder.directory(new File("D:\\Downloads\\solr-4.2.1\\solr-4.2.1\\example"));
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = r.readLine()) != null) {
                System.out.println(line);
            }
        }
}