Search code examples
javasftprace-conditionjsch

Unix Copy & JSch command is creating conflict while SFTP


I have a scenario where, first I need to copy a file from Source to Destination1 and then followed by move the same file from source to Destination2 directory.

All these three folders, Source, Destination1 and Destination2, are in the remote server. So to achieve the same I am using JSch API to make SFTP connection.

Since JSch doesn't provide any method to copy any file remotely, so I am using Unix cp command for the same. However there is rename command to move the file.

The issue is that when I am running the program file is not getting copied but moving successfully. It seems the reason is that Unix copy command is taking time to perform the action but before that move command is getting executed. Since I am using cp command of Unix, Java is not waiting (like Fire and Forget) to get the copy command completed.

To confirm my understanding on the issue I have placed sleep() after copy command and the file is copying and moving successfully. But this is not a good design.

Can someone please help me to resolve the same. Is there any way java program can wait until the Unix cp command gets executed successfully.

Below is the code snippet for copying a file:

String command1= "cp "+BackUpQueue+"/"+trimmedString+" "+HUBQueue+"/"+trimmedString ; 
channel1=session.openChannel("exec");
((ChannelExec)channel1).setCommand(command1);
channel1.setInputStream(null);
((ChannelExec)channel1).setErrStream(System.err);
InputStream in=channel1.getInputStream();
channel1.connect();
in.close();

Code for Moving a file:

channelSftp.rename(SFTPWORKINGDIR+"/"+trimmedString, BackUpQueue+"/"+trimmedString);

Solution

  • You have to wait for the "exec" channel to complete/close before you can safely run the rename on the "sftp" channel.

    For implementation, see Sending commands to server via JSch shell channel.