public boolean sendFile(final String hostname, final String username, final String password, final String remotePath,
final File file, final String destinationFileName)
{
boolean allDone = false;
FTPClient ftpClient = new FTPClient();
try
{
int reply;
ftpClient.connect(hostname);
reply = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply))
{
throw new RuntimeException("Unable to connect to ftp server");
}
if(!ftpClient.login(username, password))
{
throw new RuntimeException("Unable to login to ftp server");
}
if(!ftpClient.changeWorkingDirectory(remotePath))
{
throw new RuntimeException("Unable to change working directory");
}
if(!ftpClient.setFileType(FTP.ASCII_FILE_TYPE))
{
throw new RuntimeException("Unable to set file mode ");
}
String tempFileName = destinationFileName + FILEEXT_TEMP;
FileInputStream fis = new FileInputStream(file);
try
{
ftpClient.storeFile(tempFileName, fis);
fis.close();
}
finally
{
fis.close();
}
String finalFileName = destinationFileName;
if(!ftpClient.rename(tempFileName, finalFileName))
{
if(!ftpClient.deleteFile(tempFileName))
{
LOG.warn("Unable to delete temp file");
}
throw new RuntimeException("Unable to rename file");
}
ftpClient.logout();
allDone = true;
}
catch (Exception e)
{
LOG.fatal("Unable to FTP file", e);
}
finally
{
if(ftpClient.isConnected())
{
try
{
ftpClient.disconnect();
}
catch (IOException e)
{
LOG.warn("Erro while disconnecting from FTP", e);
}
}
}
return allDone;
}
FTP source code
最新推荐文章于 2020-09-24 20:05:32 发布
本文提供了一个使用Java实现的FTP文件上传示例代码。该方法通过连接FTP服务器、登录、改变工作目录、设置文件类型等步骤,实现了将本地文件上传到指定路径的功能,并对临时文件进行了重命名和清理。
5983

被折叠的 条评论
为什么被折叠?



