java使用Apache工具集实现ftp文件传输代码详解

2025-05-29 0 17

本文主要介绍如何使用Apache工具集commons-net提供的ftp工具实现向ftp服务器上传和下载文件。

一、准备

需要引用commons-net-3.5.jar包。

使用maven导入:

?

1

2

3

4

5
<dependency>

<groupId>commons-net</groupId>

<artifactId>commons-net</artifactId>

<version>3.5</version>

</dependency>

二、连接FTP Server

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65
/**

* 连接FTP Server

* @throws IOException

*/

public static final String ANONYMOUS_USER="anonymous";

private FTPClient connect(){

FTPClient client = new FTPClient();

try{

//连接FTP Server

client.connect(this.host, this.port);

//登陆

if(this.user==null||"".equals(this.user)){

//使用匿名登陆

client.login(ANONYMOUS_USER, ANONYMOUS_USER);

} else{

client.login(this.user, this.password);

}

//设置文件格式

client.setFileType(FTPClient.BINARY_FILE_TYPE);

//获取FTP Server 应答

int reply = client.getReplyCode();

if(!FTPReply.isPositiveCompletion(reply)){

client.disconnect();

return null;

}

//切换工作目录

changeWorkingDirectory(client);

System.out.println("===连接到FTP:"+host+":"+port);

}

catch(IOException e){

return null;

}

return client;

}

/**

* 切换工作目录,远程目录不存在时,创建目录

* @param client

* @throws IOException

*/

private void changeWorkingDirectory(FTPClient client) throws IOException{

if(this.ftpPath!=null&&!"".equals(this.ftpPath)){

Boolean ok = client.changeWorkingDirectory(this.ftpPath);

if(!ok){

//ftpPath 不存在,手动创建目录

StringTokenizer token = new StringTokenizer(this.ftpPath,"\\\\//");

while(token.hasMoreTokens()){

String path = token.nextToken();

client.makeDirectory(path);

client.changeWorkingDirectory(path);

}

}

}

}

/**

* 断开FTP连接

* @param ftpClient

* @throws IOException

*/

public void close(FTPClient ftpClient) throws IOException{

if(ftpClient!=null && ftpClient.isConnected()){

ftpClient.logout();

ftpClient.disconnect();

}

System.out.println("!!!断开FTP连接:"+host+":"+port);

}

host:ftp服务器ip地址
port:ftp服务器端口
user:登陆用户
password:登陆密码
登陆用户为空时,使用匿名用户登陆。
ftpPath:ftp路径,ftp路径不存在时自动创建,如果是多层目录结构,需要迭代创建目录。

三、上传文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47
/**

* 上传文件

* @param targetName 上传到ftp文件名

* @param localFile 本地文件路径

* @return

*/

public Boolean upload(String targetName,String localFile){

//连接ftp server

FTPClient ftpClient = connect();

if(ftpClient==null){

System.out.println("连接FTP服务器["+host+":"+port+"]失败!");

return false;

}

File file = new File(localFile);

//设置上传后文件名

if(targetName==null||"".equals(targetName))

targetName = file.getName();

FileInputStream fis = null;

try{

long now = System.currentTimeMillis();

//开始上传文件

fis = new FileInputStream(file);

System.out.println(">>>开始上传文件:"+file.getName());

Boolean ok = ftpClient.storeFile(targetName, fis);

if(ok){

//上传成功

long times = System.currentTimeMillis() - now;

System.out.println(String.format(">>>上传成功:大小:%s,上传时间:%d秒", formatSize(file.length()),times/1000));

} else//上传失败

System.out.println(String.format(">>>上传失败:大小:%s", formatSize(file.length())));

}

catch(IOException e){

System.err.println(String.format(">>>上传失败:大小:%s", formatSize(file.length())));

e.printStackTrace();

return false;

}

finally{

try{

if(fis!=null)

fis.close();

close(ftpClient);

}

catch(Exception e){

}

}

return true;

}

四、下载文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58
/**

* 下载文件

* @param localPath 本地存放路径

* @return

*/

public int download(String localPath){

// 连接ftp server

FTPClient ftpClient = connect();

if(ftpClient==null){

System.out.println("连接FTP服务器["+host+":"+port+"]失败!");

return 0;

}

File dir = new File(localPath);

if(!dir.exists())

dir.mkdirs();

FTPFile[] ftpFiles = null;

try{

ftpFiles = ftpClient.listFiles();

if(ftpFiles==null||ftpFiles.length==0)

return 0;

}

catch(IOException e){

return 0;

}

int c = 0;

for (int i=0;i<ftpFiles.length;i++){

FileOutputStream fos = null;

try{

String name = ftpFiles[i].getName();

fos = new FileOutputStream(new File(dir.getAbsolutePath()+File.separator+name));

System.out.println("<<<开始下载文件:"+name);

long now = System.currentTimeMillis();

Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos);

if(ok){

//下载成功

long times = System.currentTimeMillis() - now;

System.out.println(String.format("<<<下载成功:大小:%s,上传时间:%d秒", formatSize(ftpFiles[i].getSize()),times/1000));

c++;

} else{

System.out.println("<<<下载失败");

}

}

catch(IOException e){

System.err.println("<<<下载失败");

e.printStackTrace();

}

finally{

try{

if(fos!=null)

fos.close();

close(ftpClient);

}

catch(Exception e){

}

}

}

return c;

}

格式化文件大小

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
private static final DecimalFormat DF = new DecimalFormat("#.##");

/**

* 格式化文件大小(B,KB,MB,GB)

* @param size

* @return

*/

private String formatSize(long size){

if(size<1024){

return size + " B";

}else if(size<1024*1024){

return size/1024 + " KB";

}else if(size<1024*1024*1024){

return (size/(1024*1024)) + " MB";

}else{

double gb = size/(1024*1024*1024);

return DF.format(gb)+" GB";

}

}

五、测试

?

1

2

3

4

5

6
public static void main(String args[]){

FTPTest ftp = new FTPTest("192.168.1.10",21,null,null,"/temp/2016/12");

ftp.upload("newFile.rar", "D:/ftp/TeamViewerPortable.rar");

System.out.println("");

ftp.download("D:/ftp/");

}

结果

?

1

2

3

4

5

6

7

8

9
===连接到FTP:192.168.1.10:21

>>>开始上传文件:TeamViewerPortable.rar

>>>上传成功:大小:5 MB,上传时间:3

!!!断开FTP连接:192.168.1.10:21

===连接到FTP:192.168.1.10:21

<<<开始下载文件:newFile.rar

<<<下载成功:大小:5 MB,上传时间:4

!!!断开FTP连接:192.168.1.10:21

总结

以上就是本文关于java使用Apache工具集实现ftp文件传输代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/zleven/article/details/53886764

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java使用Apache工具集实现ftp文件传输代码详解 https://www.kuaiidc.com/113411.html

相关文章

发表评论
暂无评论