whyclj
2020-10-23 291d27a34b52911dbcfd8232f0685d34b0fc96a8
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package com.dev.ftpbackup;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
  
import org.apache.log4j.Logger;
      
    public class FTPFileUpdateDown {
        private FTPClient ftpClient;
        private String strIp;
        private int intPort;
        private String user;
        private String password;
      
        private static Logger logger = Logger.getLogger(FTPFileUpdateDown.class.getName());
      
        /* * 
         * Ftp构造函数 
         */  
        public FTPFileUpdateDown(String strIp, int intPort, String user, String Password) {
            this.strIp = strIp;
            this.intPort = intPort;
            this.user = user;
            this.password = Password;
            this.ftpClient = new FTPClient();
        }
        /** 
         * @return 判断是否登入成功 
         * */  
        public boolean ftpLogin() {
            boolean isLogin = false;
            FTPClientConfig ftpClientConfig = new FTPClientConfig();
            ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
            this.ftpClient.setControlEncoding("GBK");
            this.ftpClient.configure(ftpClientConfig);
            try {
                if (this.intPort > 0) {
                    this.ftpClient.connect(this.strIp, this.intPort);
                }else {
                    this.ftpClient.connect(this.strIp);
                }
                // FTP服务器连接回答  
                int reply = this.ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    this.ftpClient.disconnect();
                    logger.error("登录FTP服务失败!");
                    return isLogin;
                }
                this.ftpClient.login(this.user, this.password);
                // 设置传输协议  
                this.ftpClient.enterLocalPassiveMode();
                this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                
                
             // 获取登录信息
                FTPClientConfig config = new FTPClientConfig(this.ftpClient.getSystemType().split(" ")[0]);
                config.setServerLanguageCode("zh");
                this.ftpClient.configure(config);
                // 使用被动模式设为默认
                this.ftpClient.enterLocalPassiveMode();
                
                logger.info("恭喜" + this.user + "成功登陆FTP服务器");
                isLogin = true;
            }catch (Exception e) {
                e.printStackTrace();
                logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
            }
            this.ftpClient.setBufferSize(1024 * 2);
            this.ftpClient.setDataTimeout(30 * 1000);
            return isLogin;
        }
      
        /** 
         * @退出关闭服务器链接 
         * */  
        public void ftpLogOut() {
            if (null != this.ftpClient && this.ftpClient.isConnected()) {
                try {
                    boolean reuslt = this.ftpClient.logout();// 退出FTP服务器  
                    if (reuslt) {
                        logger.info("成功退出服务器");
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                    logger.warn("退出FTP服务器异常!" + e.getMessage());
                }finally {
                    try {
                        this.ftpClient.disconnect();// 关闭FTP服务器的连接  
                    }catch (IOException e) {
                        e.printStackTrace();
                        logger.warn("关闭FTP服务器的连接异常!");
                    }
                }
            }
        }
      
        /*** 
         *     上传Ftp文件 
         * @param localFile 当地文件 
         * @param romotUpLoadePath上传服务器路径 - 应该以/结束 
         * */  
        public boolean uploadFile(File localFile, String romotUpLoadePath) {
            BufferedInputStream inStream = null;
            boolean success = false;
            try {
                this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径  
                inStream = new BufferedInputStream(new FileInputStream(localFile));
                logger.info(localFile.getName() + "开始上传.....");
                success = this.ftpClient.storeFile(localFile.getName(), inStream);
                if (success == true) {
                    logger.info(localFile.getName() + "上传成功");
                    return success;
                }
            }catch (FileNotFoundException e) {
                e.printStackTrace();
                logger.error(localFile + "未找到");
            }catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (inStream != null) {
                    try {
                        inStream.close();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return success;
        }
      
        /*** 
         * 下载文件 
         * @param remoteFileName   待下载文件名称 
         * @param localDires 下载到当地那个路径下 
         * @param remoteDownLoadPath remoteFileName所在的路径 
         * */  
      
        public boolean downloadFile(String remoteFileName, String localDires,  
                String remoteDownLoadPath) {
            String strFilePath = localDires + remoteFileName;
            BufferedOutputStream outStream = null;
            boolean success = false;
            try {
                this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
                outStream = new BufferedOutputStream(new FileOutputStream(  
                        strFilePath));
                logger.info(remoteFileName + "开始下载....");
                success = this.ftpClient.retrieveFile(remoteFileName, outStream);
                if (success == true) {
                    logger.info(remoteFileName + "成功下载到" + strFilePath);
                    return success;
                }
            }catch (Exception e) {
                e.printStackTrace();
                logger.error(remoteFileName + "下载失败");
            }finally {
                if (null != outStream) {
                    try {
                        outStream.flush();
                        outStream.close();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (success == false) {
                logger.error(remoteFileName + "下载失败!!!");
            }
            return success;
        }
      
        /*** 
         * @上传文件夹 
         * @param localDirectory 
         *            当地文件夹 
         * @param remoteDirectoryPath 
         *            Ftp 服务器路径 以目录"/"结束 
         * */  
        public boolean uploadDirectory(String localDirectory,  
                String remoteDirectoryPath) {
            File src = new File(localDirectory);
            try {
                remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
                boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);
                System.out.println("localDirectory : " + localDirectory);
                System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
                System.out.println("src.getName() : " + src.getName());
                System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
                System.out.println("makeDirFlag : " + makeDirFlag);
                // ftpClient.listDirectories();
            }catch (IOException e) {
                e.printStackTrace();
                logger.info(remoteDirectoryPath + "目录创建失败");
            }
            File[] allFile = src.listFiles();
            for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    String srcName = allFile[currentFile].getPath().toString();
                    uploadFile(new File(srcName), remoteDirectoryPath);
                }
            }
            for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    // 递归  
                    uploadDirectory(allFile[currentFile].getPath().toString(),  
                            remoteDirectoryPath);
                }
            }
            return true;
        }
      
        /*** 
         * @下载文件夹 
         * @param localDirectoryPath本地地址 
         * @param remoteDirectory 远程文件夹 
         * */  
        public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
            try {
                String fileName = new File(remoteDirectory).getName();
                localDirectoryPath = localDirectoryPath + fileName + "//";
                new File(localDirectoryPath).mkdirs();
                FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
                for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
                    if (!allFile[currentFile].isDirectory()) {
                        downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
                    }
                }
                for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
                    if (allFile[currentFile].isDirectory()) {
                        String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
                        downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
                logger.info("下载文件夹失败");
                return false;
            }
            return true;
        }
        // FtpClient的Set 和 Get 函数  
        public FTPClient getFtpClient() {
            return ftpClient;
        }
        public void setFtpClient(FTPClient ftpClient) {
            this.ftpClient = ftpClient;
        }
          
        public static void main(String[] args) throws IOException {
            FTPFileUpdateDown ftp=new FTPFileUpdateDown("192.168.10.221",21,"test","123456");
            System.out.println(ftp.ftpLogin());
            //上传文件夹  
            //boolean uploadFlag = ftp.uploadDirectory("D:\\temp\\", "/"); //如果是admin/那么传的就是所有文件,如果只是/那么就是传文件夹
            //System.out.println("uploadFlag : " + uploadFlag);
            //下载文件夹  
            ftp.downLoadDirectory("d:\\123456\\", "/");
            ftp.ftpLogOut();
        }
}