【问题标题】:Concatenation in exec() method Javaexec() 方法 Java 中的连接
【发布时间】:2018-01-05 10:08:52
【问题描述】:

假设代码如下:

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();
}

【问题讨论】:

  • 这段代码无法编译,int i = 1 返回 1,这不是 if 语句中需要的布尔值。
  • 是的,当然可以。您为什么不这样做,修复编译错误,对其进行测试,然后修复您会发现的错误?

标签: java eclipse


【解决方案1】:

是的,这真的很基本......

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();

【讨论】:

    【解决方案2】:

    字符串路径="D:\Soft\Eclipse\WorkSpace\";

    int i = 0;

    如果(i ==1){

    String newpath = "perl"+path+"FirstPerl.pl";

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

    }否则如果(i == 2){

    String newpath = "perl"+path+"secondPerl.pl";

    进程=Runtime.getRuntime().exec(newpath);

    process.waitFor();

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-28
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多