java用FTP实现上传、下载文

FTPClient的jar包下载地址:
http://commons.apache.org/proper/commons-net/download_net.cgi
在commons-net-3.6.jar里面

文件上传:
public static void main(String[] args) {
		ftpUpload("223.105.1.100", "cmsoftu****", "syzw****", "E:\\recordfilecopy\\record1.txt", "/home/cmsoftu/detail/", "record1.txt");
	}

	public static void ftpUpload(String url, String username, String password, String localfilepath, String serverpath, String filename) {

		FTPClient ftpClient = new FTPClient();
		// 创建ftp连接。默认是21端口
		try {
			ftpClient.connect(url, 21);
			ftpClient.login(username, password);
			// 读取本地文件
			FileInputStream inputStream = new FileInputStream(new File(localfilepath));
			// 设置上传的路径
			ftpClient.changeWorkingDirectory(serverpath);
			// 修改上传文件的格式
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			// 第一个参数:服务器端文档名(即上传到服务器上的文件名)
			// 第二个参数:上传文档的inputStream
			ftpClient.storeFile(filename, inputStream);
			ftpClient.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}

	}
文件下载:
public static void main(String[] args) {
		ftpDownloadFile("223.105.1.100", "cmsoftu****", "syzw****", "E:\\recordfile", "/home/cmsoftu/detailcopy", "record1.txt");
	}

public static boolean ftpDownloadFile(String url, String username, String password, String localPath, String remotePath, String fileName) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, 21);
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(remotePath);
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值