我如何在 运行 时间将中间的字符串连接到字符串?

How do i concatenate a string in between to strings at run time?

我有一个需要检查文件是否存在的用例。但要注意的是,有不同的文件需要检查,每个文件都有自己的方法。

static String  fileToCheck="";
static String  commandToCheckIfFileExists="test -e "+ fileToCheck+ " && echo file exists || echo file not found" //This command checks if file exists in server.

void checkForABCFile(){
    fileToCheck="/path/to/file/ABC.txt";
    NAMServerLogin con = new NAMServerLogin();
    con.connect(sshHost, sshUsername, sshPassword)
    log.debug(commandToCheckIfFileExists)
    String fileCheckOutput=con.execShellCommand(commandToCheckIfFileExists,true);
    Assert.assertTrue(fileCheckOutput.equals("echo file exists"),'ABC file does not exist')
        
}
void checkForXYZFile(){
    fileToCheck="/path/to/file/XYZ.txt";
    ServerLogin con = new ServerLogin();  //Custom class which connects to terminal
    con.connect(sshHost, sshUsername, sshPassword)
    log.debug(commandToCheckIfFileExists)
    String fileCheckOutput=con.execShellCommand(commandToCheckIfFileExists,true);
    Assert.assertTrue(fileCheckOutput.equals("echo file exists"),'ABC file does not exist')
 
}

我尝试了上面的代码片段,调试记录了这个 test -e && echo file exists || echo file not found

字符串变量 fileToCheck 未在命令中更新。

有没有实现运行时间串拼接的方案?

String variable fileToCheck is not getting updated in the command.

不,不会更新。它在字段初始化时计算一次,使用当时fileToCheck的值。

每次需要的时候写一个方法来求值:

static String getCommandToCheckIfFileExists(String fileToCheck) {
  return "test -e "+ fileToCheck+ " && echo file exists || echo file not found";
}

然后调用这个:

String fileCheckOutput=con.execShellCommand(getCommandToCheckIfFileExists(fileToCheck),true);

请注意,您不再需要静态字段 fileToCheck - 为此设置静态字段并不是一个好主意,因为

  1. 你可能忘记设置了,所以不小心查看了之前的文件
  2. 两个线程可能会互相踩踏,将其设置为不同的值;在没有任何同步的情况下,没有定义每个线程将使用哪个值。