Trying to rename a file/folder using JSch API executing them as shell commands is not working. mkdir
and rmdir
are working fine.
JDK version – 11.
JSch version – 0.1.55.
Using the following code.
ChannelExec execChannel = null;
try {
execChannel = (ChannelExec) session.openChannel("exec");
execChannel.connect();
execChannel.setCommand("rename dir1 dir2");
execChannel.start();
} catch (JSchException ex) {
throw new IOException(ex);
} finally {
if (execChannel != null) {
execChannel.disconnect();
}
}
Update:
- The SFTP server is hosted on a CentOS machine
mv
,ren
,rename
– None of them worked- How do we know the command did not work – The folder name is still the old name. Also the
execChannel.getExitStatus()
gives-1
. No error is thrown
2
Answers
If you are using Jsch I believe that the remote host is a Unix-like system. There is no command
rename
in Unix. Usemv
instead.You are most probably executing a wrong command. If you are connecting to Linux, the command to use is
mv
.Though, you should not use shell commands for trivial file operations like creating and removing a directory and renaming a file/directory. That’s a very fragile approach.
Instead, use the the standard file management API of SSH, the SFTP (
ChannelSftp
in JSch).