2022-05-30FTPClient实现FTP上传与下载

JAVA实现FTP上传与下载

JAVA操作FTP服务器,只需要创建一个FTPClient即可,所有的操作都封装在FTPClient中,JDK自带的有FTPClient(sun.net.ftp.FtpClient),也可以用第三方的FTPClient,一般使用apache的FTPClient(org.apache.commons.net.ftp.FTPClient),本文将使用apache的FTPClient,API都大同小异

关键依赖:commons-net

对常用操作(上传、下载)封装成工具类

package com.day0322;

import org.apache.commons.io.IOUtils;

import org.apache.commons.lang3.StringUtils;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPReply;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

/**

* FTP工具类

* 文件上传

* 文件下载

*/

public class FTPUtil {

    private static final Logger log = LoggerFactory.getLogger(FTPUtil.class);

    /**

    * 设置缓冲区大小4M

    **/

    private static final int BUFFER_SIZE = 1024 * 1024 * 4;

    /**

    * 本地字符编码

    **/

    private static String LOCAL_CHARSET = "GBK";

    /**

    * UTF-8字符编码

    **/

    private static final String CHARSET_UTF8 = "UTF-8";

    /**

    * OPTS UTF8字符串常量

    **/

    private static final String OPTS_UTF8 = "OPTS UTF8";

    /**

    * FTP协议里面,规定文件名编码为iso-8859-1

    **/

    private static final String SERVER_CHARSET = "ISO-8859-1";

    private static FTPClient ftpClient = null;

    /**

    * 连接FTP服务器

    */

    private static void login(OaFtp oaFtp) {

        ftpClient = new FTPClient();

        try {

            ftpClient.connect(oaFtp.getIp(), Integer.valueOf(oaFtp.getPort()));

            ftpClient.login(oaFtp.getName(), oaFtp.getPwd());

            ftpClient.setBufferSize(BUFFER_SIZE);

            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            int reply = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {

                closeConnect();

            }

        } catch (Exception e) {

            log.error("",e);

            throw new RuntimeException(e);

        }

    }

    /**

    * 关闭FTP连接

    */

    private static void closeConnect() {

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

            try {

                ftpClient.logout();

                ftpClient.disconnect();

            } catch (IOException e) {

                log.error("",e);

            }

        }

    }

    /**

    * FTP服务器路径编码转换

    *

    * @param ftpPath FTP服务器路径

    * @return String

    */

    private static String changeEncoding(String ftpPath) {

        String directory = null;

        try {

            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {

                LOCAL_CHARSET = CHARSET_UTF8;

            }

            directory = new String(ftpPath.getBytes(LOCAL_CHARSET), SERVER_CHARSET);

        } catch (Exception e) {

            log.error("",e);

        }

        return directory;

    }

    /**

    * 改变工作目录

    * 如果没有,则创建工作目录

    * @param path

    */

    private static void changeAndMakeWorkingDir(String path) {

        try {

            ftpClient.changeWorkingDirectory("/");

            path = path.replaceAll("\\\\","/");

            String[] path_array = path.split("/");

            for (String s : path_array) {

                boolean b = ftpClient.changeWorkingDirectory(s);

                if (!b) {

                    ftpClient.makeDirectory(s);

                    ftpClient.changeWorkingDirectory(s);

                }

            }

        } catch (IOException e) {

            log.error("",e);

            throw new RuntimeException(e);

        }

    }

    /**

    * 上传

    * @param oaFtp

    * @param filename

    * @param dirPath

    * @param in

    * @return

    */

    public static boolean upload (OaFtp oaFtp, String filename, String dirPath, InputStream in) {

        login(oaFtp);

        if (!ftpClient.isConnected()) {

            return false;

        }

        boolean isSuccess = false;

        if (ftpClient != null) {

            try {

                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {

                    LOCAL_CHARSET = CHARSET_UTF8;

                }

                ftpClient.setControlEncoding(LOCAL_CHARSET);

                String path = changeEncoding(dirPath);

                changeAndMakeWorkingDir(path);

                isSuccess = ftpClient.storeFile(new String(filename.getBytes(), SERVER_CHARSET), in);

            } catch (Exception e) {

                log.error("",e);

            } finally {

                closeConnect();

            }

        }

        return isSuccess;

    }

    /**

    * 下载

    * @param oaFtp

    * @param filename

    * @param dirPath

    * @param out

    * @return

    */

    public static void download (OaFtp oaFtp, String filename, String dirPath, FileOutputStream out) {

        // 登录

        login(oaFtp);

        if (ftpClient != null) {

            try {

                String path = changeEncoding(dirPath);

                changeAndMakeWorkingDir(path);

                String[] fileNames = ftpClient.listNames();

                if (fileNames == null || fileNames.length == 0) {

                    return;

                }

                for (String fileName : fileNames) {

                    String ftpName = new String(fileName.getBytes(SERVER_CHARSET), LOCAL_CHARSET);

                    if (StringUtils.equals(ftpName,filename)) {

                        InputStream in = ftpClient.retrieveFileStream(fileName);

                        IOUtils.copy(in,out);

                    }

                }

            } catch (IOException e) {

                log.error("",e);

            } finally {

                closeConnect();

            }

        }

    }

}

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

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

测试

1.上传

2.下载

————————————————

版权声明:本文为CSDN博主「hehuijava」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/hehuihh/article/details/115124225

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。