How to move file from directory A to directory B in remote server?

前提是你 提交于 2019-12-30 10:44:14

问题


I am using JSch to connect to SFTP in a website which is made from GWT. I had read a little example of sftpChannel.get(), sftpChannel.rename(), sftpChannel.rm()

But I didn't find a solution that copy a file from remote server a directory to remote server b directory.

For example, I want to copy file from /appl/user/home/test/temp to /appl/user/home/test/. Filename = abc.jpg.

I stunned here for few hours since most of the solution from network is getting file from remote server to local, or uploading file from local to remote server.

String existingfile = "abc.jpg";
String newfile = "123.jpg";
FileDirectory = "/appl/user/home/test/";
sftp.cd(FileDirectory+"temp/");
sftp.rename(newfile, FileDirectory+newfile);

Let's say, abc.jpg is existing in /appl/user/home/test/

And I upload a 123.jpg in /appl/user/home/test/temp/.

Now, I want to move 123.jpg to /appl/user/home/test/ and remove abc.jpg in /appl/user/home/test/.

What should I do?


回答1:


It seems like SftpChannel.rename(); need to use full path of file instead of cd to the directory that the file I am going to move.

String existingfile = "abc.jpg";
String newfile = "123.jpg";
FileDirectory = "/appl/user/home/test/";
sftp.cd(FileDirectory+"temp/");
if (sftp.get( newfile ) != null){
    sftp.rename(FileDirectory + "temp/" + newfile , 
        FileDirectory + newfile );
    sftp.cd(FileDirectory);
    sftp.rm(existingfile );
}



回答2:


A core SFTP protocol does not support duplicating a remote file.

There's draft of copy-file extension to the protocol, but that's supported by only few SFTP servers (ProFTPD/mod_sftp and Bitvise SFTP server for example).

The JSch library does not support the copy-file extension either.

Alternatives:

  • If you have a shell access, open an "exec" channel, and use shell cp command (or equivalent command for your server's OS).
    See Exec.java example.
  • Otherwise, your only option is to download the file to a local temporary location and upload its copy back to a different/target remote directory. Or use the streams, to avoid a temporary file.

See also How can I copy/duplicate a file to another directory using SFTP?




回答3:


You can write a normal Java FileInputStreamand FileOutputStreamcode and instead of using paths like these /appl/user/home/test/temp use full path with its IpAddress or remote server name + your path eg myremoteserver/appl/user/home/test/temp



来源:https://stackoverflow.com/questions/30050045/how-to-move-file-from-directory-a-to-directory-b-in-remote-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!