如何将文件从远程服务器中的目录A移动到目录B?

问题描述 投票:0回答:3

我正在使用 JSch 连接到由 GWT 制作的网站中的 SFTP。 我读过一个小例子

sftpChannel.get()
,
sftpChannel.rename()
,
sftpChannel.rm()

但是我没有找到将文件从远程服务器

a
目录复制到远程服务器
b
目录的解决方案。

例如,我想将文件从

/appl/user/home/test/temp
复制到
/appl/user/home/test/
。文件名 =
abc.jpg
.

我在这里震惊了几个小时,因为大多数网络解决方案都是从远程服务器获取文件到本地,或者从本地上传文件到远程服务器。

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

假设,

abc.jpg
存在于
/appl/user/home/test/

我在

123.jpg
上传了
/appl/user/home/test/temp/

现在,我想将

123.jpg
移至
/appl/user/home/test/
并删除
abc.jpg
中的
/appl/user/home/test/

我该怎么办?

java sftp jsch
3个回答
10
投票

看起来

SftpChannel.rename();
需要使用文件的完整路径而不是cd到我要移动的文件的目录。

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

0
投票
    try {
            ChannelSftp channelSftp = (ChannelSftp) this.session.openChannel("sftp");
            channelSftp.connect();              
            logger.info("Home directory: {}",channelSftp.getHome());
            logger.info("Go to directory: {}",pathSFTP);
            logger.info("Move files to directory: {} ",destinationPath);
            
            channelSftp.cd(pathSFTP);
            
            List<ChannelSftp.LsEntry> filesFound = channelSftp.ls(fileExtension);
            
            logger.info("Files [{}] found ",filesFound.size());
            
            //Move to path processed
            for (LsEntry lsEntry : filesFound) {
                String pathDes = destinationPath+"/"+lsEntry.getFilename();
                channelSftp.rename(lsEntry.getFilename(), pathDes);
                logger.info("Moved to {} ",pathDes);
            }
            
            //Close Connection
            channelSftp.exit();
            channelSftp.disconnect();
            
            logger.info("All files has been downloaded successfully");
            
        } catch (JSchException | SftpException e) {
            logger.error("Error move files directory [{}]",destinationPath);
            logger.error("An error has occurred while Move files {}", e.getMessage());
            e.printStackTrace();
        }
        }

-1
投票

您可以编写普通的 Java

FileInputStream
FileOutputStream
代码,而不是使用这样的路径
/appl/user/home/test/temp
使用完整路径及其 IpAddress 或远程服务器名称 + 您的路径,例如
myremoteserver/appl/user/home/test/temp

© www.soinside.com 2019 - 2024. All rights reserved.