`
jordan_micle
  • 浏览: 240251 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

FTP进行上传下载文件

阅读更多

需要引入外部jar包:commons-net-2.0.jar(或者是子包commons-net-ftp-2.0.jar)

 

STEP1:

 

/**
 * 连接并登录FTP 
 * @param hostname:ftp地址(不带ftp://)
 * @param username:登录用户名
 * @param password:登录密码
 **/
public int openFtp(String hostname, String username, String password) {
	int result = 0;
	
	// 第一步:实例化FTPClient
	ftpClient = new FTPClient();
	
	try {
		// 第二步:连接FTP
		ftpClient.connect(hostname);
		
		// 第三步:登录FTP
		ftpClient.login(username, password);
		
	} catch (SocketException e) {
		// 连接错误时捕捉此异常
		result = 1;
	} catch (IOException e) {
		e.printStackTrace();
	} 
	
	return result;
}

 

STEP2:

/**
 * 下载单个文件
 * 
 * @param remoteFile
 *            :需要下载的文件,格式为ftp://xx.xx.xx.xx/remoteFile,如:ftp://10.10.10.10/dir1
 *            /dir2/file.txt,则remoteFile为dir1/dir2/file.txt
 * @param localFile:下载的文件保存到本地的文件,为完整绝对路径。
 * @return
 */
public int ftpDownload(String remoteFile, String localFile) {
	FileOutputStream fos = null;
	InputStream is = null;
	try {
		// 第一步:设置基本属性
		ftpClient.setBufferSize(1024);
		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		
		// 第二步:获取远程文件的输入流
		is = ftpClient.retrieveFileStream(remoteFile);
		
		if (is == null) {
			// 如果输入流为空,则表示要下载的远程文件不存在
			return 0;
		} else {
			// 如果输入流不为空,则将远程文件的输入流写到本地
			fos = new FileOutputStream(localFile);
			byte[] buffer = new byte[1024];
			int i = -1;
			while ((i = is.read(buffer)) != -1) {
				fos.write(buffer, 0, i);
			}
		}

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		// 关闭输入输出流
		IOUtils.closeQuietly(is);
		IOUtils.closeQuietly(fos);
	}

	return 1;
}
 

STEP3:

 

STEP4:

 

/**
 * 退出登录ftp,并断开连接
 */
public void closeFtp() {
	try {
		if (ftpClient != null) {
			ftpClient.logout();
			ftpClient.disconnect();
		}
	} catch (IOException e) {
		// 断开连接错误时捕捉此异常
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics