`
sunxboy
  • 浏览: 2869820 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

FTP source code

 
阅读更多
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;
	}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics