您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用Java将FTP服务器上的文件复制到同一服务器上的目录中?

如何使用Java将FTP服务器上的文件复制到同一服务器上的目录中?

如果您使用的是apache commons netFTPClient,则有一种直接方法文件一个位置移动到另一位置(如果user具有适当的权限)。

ftpClient.rename(from, to);

或者,如果您熟悉ftp commands,可以使用类似

ftpClient.sendCommand(FTPCommand.yourCommand, args);
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
     //command successful;
} else {
     //check for reply code, and take appropriate action.
}

如果您使用任何其他客户端,请阅读文档,客户端实现之间不会有太大变化。

上面的方法文件移动到to目录,即文件from不再在目录中。基本上ftp协议意味着要从服务器中传输文件local <-> remote或从remote <-> other remote服务器中不传输文件

解决此问题的方法会更简单,将完整文件获取到本地,InputStream然后将其作为备份目录中的新文件写回到服务器。

获取完整的文件

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ftpClient.retrieveFile(fileName, outputStream);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

现在,将此流存储到备份目录。首先,我们需要将工作目录更改为备份目录。

// assuming backup directory is with in current working directory
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//binary files
ftpClient.changeWorkingDirectory("backup");
//this overwrites the existing file
ftpClient.storeFile(fileName, is);
//if you don't want to overwrite it use storeUniqueFile

希望这对您有帮助。

java 2022/1/1 18:21:10 有726人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶