在exec()方法Java中连接

时间:2018-01-05 10:08:52

标签: java eclipse

假设代码如下:

if (int i = 1) {
        process = Runtime.getRuntime().exec("perl D:\\Soft\\Eclipse\\WorkSpace\\FirstPerl.pl");
        process.waitFor();
}
else if(int i = 2) {
     process = Runtime.getRuntime().exec("perl D:\\Soft\\Eclipse\\WorkSpace\\secondPerl.pl");
     process.waitFor();
}

//so on ..

我可以通过多种方式将路径声明为D:\\Soft\\Eclipse\\WorkSpace\\并实现以下内容,而不是多次重复路径String

String path = "D:\\Soft\\Eclipse\\WorkSpace\\";
if (int i = 1) {
    process = Runtime.getRuntime().exec("perl"+path+"FirstPerl.pl");
    process.waitFor();
}
else if(int i = 2){
    process = Runtime.getRuntime().exec("perl"+path+"secondPerl.pl");
    process.waitFor();
}

2 个答案:

答案 0 :(得分:0)

是的,这是非常基本的......

String[] scripts = new String[] { "firstPerl.pl", "secondPerl.pl" };
Path script = Paths.get(path, scripts[i-1]); // or 0-base i in the first place
process = Runtime.exec("perl " + script.toAbsolutePath());
process.waitFor();

答案 1 :(得分:0)

String path =“D:\ Soft \ Eclipse \ WorkSpace \”;

int i = 0;

if(i == 1){

String newpath =“perl”+ path +“FirstPerl.pl”;

过程=调用Runtime.getRuntime()EXEC(NEWPATH); process.waitFor();

}否则if(i == 2){

String newpath =“perl”+ path +“secondPerl.pl”;

process = Runtime.getRuntime()。exec(newpath);

process.waitFor();

}