ftp链接、上传、下载、断开

开发环境:Jdk 1.8

引入第三方库:commons-net-2.2.jar(针对第一种方法)

一、基于第三方库FtpClient的FTP服务器数据传输

由于是基于第三方库,所以这里基本上没有太多要说明的东西。就是导入第三方库再调用即可,调用过程从下面的代码可以参见。为了便于文章的完整性,这也是给出其程序结构图吧。

图-1 基于FtpClient的FTP网络文件传输图

1.FTP的连接及登录

  1. public static FtpClient connectFTP(String url, int port, String username, String password) {
  2. //创建ftp
  3. FtpClient ftp = null;
  4. try {
  5. //创建地址
  6. SocketAddress addr = new InetSocketAddress(url, port);
  7. //连接
  8. ftp = FtpClient.create();
  9. ftp.connect(addr);
  10. //登陆
  11. ftp.login(username, password.toCharArray());
  12. ftp.setBinaryType();
  13. } catch (FtpProtocolException e) {
  14. e.printStackTrace();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. return ftp;
  19. }

2.上传文件到FTP服务器

  1. public static void upload(String localFile, String ftpFile, FtpClient ftp) {
  2. OutputStream os = null;
  3. FileInputStream fis = null;
  4. try {
  5. // 将ftp文件加入输出流中。输出到ftp上
  6. os = ftp.putFileStream(ftpFile);
  7. File file = new File(localFile);
  8. // 创建一个缓冲区
  9. fis = new FileInputStream(file);
  10. byte[] bytes = new byte[1024];
  11. int c;
  12. while((c = fis.read(bytes)) != -1){
  13. os.write(bytes, 0, c);
  14. }
  15. System.out.println("upload success!!");
  16. } catch (FtpProtocolException e) {
  17. e.printStackTrace();
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21. try {
  22. if(os!=null) {
  23. os.close();
  24. }
  25. if(fis!=null) {
  26. fis.close();
  27. }
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }

3.从FTP服务器下载文件

 

  1. public static void download(String localFile, String ftpFile, FtpClient ftp) {
  2. InputStream is = null;
  3. FileOutputStream fos = null;
  4. try {
  5. // 获取ftp上的文件
  6. is = ftp.getFileStream(ftpFile);
  7. File file = new File(localFile);
  8. byte[] bytes = new byte[1024];
  9. int i;
  10. fos = new FileOutputStream(file);
  11. while((i = is.read(bytes)) != -1){
  12. fos.write(bytes, 0, i);
  13. }
  14. System.out.println("download success!!");
  15. } catch (FtpProtocolException e) {
  16. e.printStackTrace();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. } finally {
  20. try {
  21. if(fos!=null) {
  22. fos.close();
  23. }
  24. if(is!=null){
  25. is.close();
  26. }
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

二、基于Socket的FTP服务器数据传输

其实上面的基于第三方包FtpClient的方法中,原理层也是基于Socket来进行通信的。所以,我们当然也可以使用Socket直接来写这个FtpClient的代码。下面给出基于Socket通信的结构构架图。这里有一点需要大家注意一下,我们的FTP协议中有两个端口(20和21)。通常情况下,我们的21号端口就是平时大家口口相传的是FTP服务器的端口号,不过其实它只是FTP服务器中的命令端口号。它是负责传送命令给FTP,一些操作如“登录”、“改变目录”、“删除文件”,依靠这个连接发送命令就可完成。而对于20号端口号(也有可能是其它的一些端口号),对于有数据传输的操作,主要是显示目录列表,上传、下载文件,我们需要依靠另一个Socket来完成。

所以在下面的结构图中,我们可以看到我们有重新获得端口号的过程,正是这个原因。

图-2 基于Socket的FTP网络文件传输图

1.FTP连接

  1. public void connectFtp() {
  2. try {
  3. mFtpClient = new Socket(Config.FTP.HOST_IP, Config.FTP.HOST_PORT);
  4. mReader = new BufferedReader(new InputStreamReader(mFtpClient.getInputStream()));
  5. mWriter = new BufferedWriter(new OutputStreamWriter(mFtpClient.getOutputStream()));
  6. sendCommand("USER " + Config.FTP.FTP_USERNAME);
  7. sendCommand("PASS " + Config.FTP.FTP_PASSWD);
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }

2.向FTP服务器发送命令

 

  1. private void sendCommand(String command) throws IOException {
  2. if (Tools.StringTools.isEmpty(command)) {
  3. return;
  4. }
  5. if (mFtpClient == null) {
  6. return;
  7. }
  8. mWriter.write(command + "\r\n");
  9. mWriter.flush();
  10. }

3.向FTP服务器上传文件

 

  1. public void uploadFile(String localPath, String ftpPath) throws IOException {
  2. // 进入被动模式
  3. sendCommand("PASV");
  4. // 获得ip和端口
  5. String response = readNewMessage();
  6. String[] ipPort = getIPPort(response);
  7. String ip = ipPort[0];
  8. int port = Integer.parseInt(ipPort[1]);
  9. // 建立数据端口的连接
  10. Socket dataSocket = new Socket(ip, port);
  11. sendCommand("STOR " + ftpPath);
  12. // 上传文件前的准备
  13. File localFile = new File(localPath);
  14. OutputStream outputStream = dataSocket.getOutputStream();
  15. FileInputStream fileInputStream = new FileInputStream(localFile);
  16. // 上传文件
  17. int offset;
  18. byte[] bytes = new byte[1024];
  19. while ((offset = fileInputStream.read(bytes)) != -1) {
  20. outputStream.write(bytes, 0, offset);
  21. }
  22. System.out.println("upload success!!");
  23. // 上传文件后的善后工作
  24. outputStream.close();
  25. fileInputStream.close();
  26. dataSocket.close();
  27. }

4.从FTP服务器下载文件

[java] view plain copy

print?

  1. public void downloadFile(String localPath, String ftpPath) throws IOException {
  2. // 进入被动模式
  3. sendCommand("PASV");
  4. // 获得ip和端口
  5. String response = readNewMessage();
  6. String[] ipPort = getIPPort(response);
  7. String ip = ipPort[0];
  8. int port = Integer.parseInt(ipPort[1]);
  9. // 建立数据端口的连接
  10. Socket dataSocket = new Socket(ip, port);
  11. sendCommand("RETR " + ftpPath);
  12. // 下载文件前的准备
  13. File localFile = new File(localPath);
  14. InputStream inputStream = dataSocket.getInputStream();
  15. FileOutputStream fileOutputStream = new FileOutputStream(localFile);
  16. // 下载文件
  17. int offset;
  18. byte[] bytes = new byte[1024];
  19. while ((offset = inputStream.read(bytes)) != -1) {
  20. fileOutputStream.write(bytes, 0, offset);
  21. }
  22. System.out.println("download success!!");
  23. // 下载文件后的善后工作
  24. inputStream.close();
  25. fileOutputStream.close();
  26. dataSocket.close();
  27. }

5.断开FTP服务器连接

[java] view plain copy

print?

    1. public void disconnectFtp() {
    2. if (mFtpClient == null) {
    3. return;
    4. }
    5. if (!mFtpClient.isConnected()) {
    6. return;
    7. }
    8. try {
    9. mFtpClient.close();
    10. } catch (IOException e) {
    11. e.printStackTrace();
    12. }
    13. }
时间: 2024-08-01 10:44:49

ftp链接、上传、下载、断开的相关文章

****使用ftp软件上传下载php文件时换行符丢失bug

在使用ftp软件上传下载php源文件时,我们偶尔会发现在本地windows下notepad++编辑器写好的php文件,在使用ftp上传到linux服务器后,php文件的换行符全部丢失了,导致php文件无法正常运行. 这个时候,再次通过ftp软件把刚才上传的php文件下载到本地windows,用notepad++编辑器打开后,发现php源代码变成了一行,换行丢失. 发生这种情况的原因是什么呢?飘易就以一句话概括下:    由于linux下换行是\n,而windows下换行是\r\n,当ftp软件在

FTP文件上传下载及验证

FTP文件上传下载及验证 有时候经常用到FTP的上传下载,本身代码相对比较简单,但有时需要考虑到文件上传下载进行验证.大体思路是上传时将FTP日志重定向到本地文件,再根据FTP返回码进行检查,这样有个缺点就是不能检验文件上传的完整性:下载时利用ls,ll命令查看是否存在. 上传代码 uploadFile() { ftp -i -v -n <<! >/tmp/ftp.log open $FTP_IP $FTP_PORT user $USER_ID $PASSWORD prompt cd $

【FTP】FTP文件上传下载-支持断点续传

Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常用)]和[ASCII_FILE_TYPE]两种; 数据连接模式:一般使用LocalPassiveMode模式,因为大部分客户端都在防火墙后面: 1. LocalPassiveMode:服务器端打开数据端口,进行数据传输: 2. LocalActiveMode:客户端打开数据端口,进行数据传输: 系统

Java通过FTP服务器上传下载文件的解决方案

对于使用文件进行交换数据的应用来说,使用FTP 服务器是一个很不错的解决方案.本文使用Apache Jakarta Commons Net(commons-net-3.3.jar)基于FileZilla Server服务器实现FTP服务器上文件的上传/下载/删除等操作. 关于FileZilla Server服务器的详细搭建配置过程,详情请见FileZilla Server安装配置教程.之前有朋友说,上传大文件(几百M以上的文件)到FTP服务器时会重现无法重命名的问题,但本人亲测上传2G的文件到F

JMeter创建FTP测试服务器上传下载性能

在工作中,有时候我们会对服务器的上传下载性能进行测试,于是就整理了工作中测试ftp上传下载的是实战总结. 测试环境: jmeter 我使用的是apache-jmeter-2.13 测试服务器是阿里云上的真实服务器,IP:***.***.***.*** (为了服务器安全,我就不写那么精确的IP地址了.)但是被测服务器上必须按照ftp服务端,有ftp账号,如果这里不明白可以留言. 1,创建一个线程组 2.线程组--->添加--->配置元件--->FTP请求缺省值. 3.线程组--->添

FTP客户端上传下载实现

1.第一次感觉MS也有这么难用的MFC类: 2.CFtpFileFind类只能实例化一个,多个实例同时查找会出错(因此下载时不能递归): 3.本程序支持文件夹嵌套上传下载: 4.boost::filesystem::create_directory不能递归创建文件夹,需手动实现 代码如下: CFtpClient.h 1 #ifndef __ftp_client_h__ 2 #define __ftp_client_h__ 3 4 #include <afxinet.h> 5 #include

winform通过FTP协议上传下载文件

上传文件:窗体代码 一次上传多个文件(grdAffixFilesList中需要上传的) private Boolean UploadFile() { string filename; int upCount=0; for (int i = 0; i < this.grdAffixFilesList.Rows.Count; i++) { filename = this.grdAffixFilesList.Rows[i].Cells["FILEPATH"].Text.ToString

ftp文件服务器上传下载案例

Vsftpd是very secure FTP daemon(非常安全的FTP守护进程) 21端口 控制连接 20端口 数据连接 在Linux安装vsftpd后 默认匿名用户与本地用户都可以登录 匿名用户登陆到/var/ftp,不能上传和下载 本地用户登陆到本地用户的家目录,可以上传和下载 Linux  Client(192.168.2.2) -------RHEL5.9(vmnet1)--------(vmnet1) 192.168.2.1                   Win7  Cli

Spring中利用组件实现从FTP服务器上传/下载文件

FtpUtil.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.ne

Java 利用Apache Commons Net 实现 FTP文件上传下载

package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Comparator;