Reputation: 11
I managed to create a method which uploads a file into a directory.
How would I have to change this so I could copy a file from /123.html to /en/123.html via JSch?
public void upFile(String source, String fileName, String destination) throws Exception {
try {
try {
// 改变当前路径
client.cd(destination);
} catch (Exception e) {
System.out.println("当前目录不存在,新建目录!");
JschCreateDir.createDir(host, port, username, password, destination);
client.cd(destination);
}
// 上传本地文件 到当前目录
File file = new File(source + fileName);
client.put(new FileInputStream(file), fileName);
} catch (Exception e) {
logout();
throw e;
}
}
Upvotes: 1
Views: 3947
Reputation: 74750
I understand your question that you want to copy a file on the server from one directory to another one (and not a local file to the server, which your code already seems to do).
Unfortunately, the SFTP protocol (which is implemented by JSch's ChannelSFTP class) doesn't support copying directly on the server.
You certainly can combine the put
and get
to copy the file from one location to another, but this will send the contents twice through the wire from server to client and back.
A better way would be to use an exec
channel, and simply directly issue the server's system's copy command. On a unixoid server, this would be cp /123.html /en/123.html
. (This assumes you have shell access to the server, not an sftp-only access, as I already did see somewhere.)
Here is some code (not tested, you might need to add exception handling):
public void copyFile(Session session, String sourceFile, String destinationFile) {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("cp " + sourceFile + " " + destinationFile);
channel.connect();
while(channel.isConnected()) {
Thread.sleep(20);
}
int status = channel.getExitStatus();
if(status != 0)
throw new CopyException("copy failed, exit status is " + status);
}
Upvotes: 2