Skip to content
Advertisement

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

I have use case where I need to check if a file exists. But the catch is, there are diffrent file that needs to checked for and each file will have its own method.

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')
 
}

I tried the above code snippet, the debug logs this test -e && echo file exists || echo file not found.

String variable fileToCheck is not getting updated in the command.

Is there any solution to achieve run time string concatenation?

Advertisement

Answer

String variable fileToCheck is not getting updated in the command.

No, it wouldn’t be updated. It’s evaluated once when the field is initialized, using the value of fileToCheck at that time.

Write a method to evaluate it each time you need it:

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

Then call this:

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

and note you don’t need the static field fileToCheck any more – having a static field for that isn’t a good idea because

  1. you might forget to set it, so you accidentally check the previous file
  2. two threads might stomp on each other, setting it to different values; and without any synchronization, it’s not defined as to which of the values would be used by each thread.
Advertisement