FTPUtils.java
8.05 KB
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
package com.topdraw.sohu.utils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class FTPUtils {
private static final Logger logger = LoggerFactory
.getLogger(FTPUtils.class);
private final String PROJECT_PATH = this.getClass().getClassLoader().getResource("../../") == null ?
(System.getProperty("user.dir").endsWith("/") ? System.getProperty("user.dir")
: System.getProperty("user.dir") + "/")
: this.getClass().getClassLoader().getResource("../../").getPath();
/**
* Description: 向FTP服务器上传文件
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
System.out.println("ReplyCode: " + reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* Description: 从FTP服务器下载文件
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downFile(
String url, int port, String username, String password, String remotePath, String fileName,
String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.setConnectTimeout(10 * 1000);
ftp.connect(url, port);
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
ftp.setBufferSize(102400);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
System.out.println("ReplyCode: " + reply);
if (!FTPReply.isPositiveCompletion(reply)) {
logger.info("isPositiveCompletion");
ftp.disconnect();
return success;
}
logger.info("remotePath: " + remotePath);
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
ftp.enterLocalPassiveMode();
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff:fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
logger.info("file size: " + ff.getSize());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
logger.info("download file size: " + localFile.length());
if (ff.getSize() == localFile.length()) {
success = true;
} else {
logger.info("file size mismatch: " + ff.getSize() + " -> " + localPath.length());
}
break;
}
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
success = false;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return success;
}
public String downFile(String strFtpPath, String strRelativePath) {
String strUrl = "", strUserName = "", strPassWord = "", strRemotePath = "", strFileName = "", strLocalPath = "";
int iPort = 21;
// 截取FTP地址
final String strFtpFlag = "ftp://";
if (strFtpPath != null && strFtpPath.length() > 0 && strFtpPath.toLowerCase().contains(strFtpFlag)) {
// 首先去掉FTP
final String cutedFtp = strFtpPath.substring(strFtpPath.indexOf(strFtpFlag) + strFtpFlag.length());
// 首先截取用户名、密码、ip、端口
String str4 = "";
if (cutedFtp.indexOf("/") != -1) {
str4 = cutedFtp.substring(0, cutedFtp.indexOf("/"));
} else {
str4 = cutedFtp;
}
// 截取用户名、密码
String strUsernameAndPwd = str4.substring(0, str4.indexOf("@"));
// 截取ip、端口
String strIpAndPort = str4.substring(str4.indexOf("@") + 1);
// 开始获取ip和端口
if (!"".equals(strIpAndPort)) {
if (strIpAndPort.indexOf(":") != -1) {
strUrl = strIpAndPort.substring(0, strIpAndPort.indexOf(":"));
String strPort = strIpAndPort.substring(strIpAndPort.indexOf(":") + 1, strIpAndPort.length());
if (strPort != null) {
iPort = Integer.parseInt(strPort);
}
} else {
// 如果没有端口只获取IP
strUrl = strIpAndPort;
}
}
// 开始获取用户名和密码
if (!"".equals(strUsernameAndPwd)) {
strUserName = strUsernameAndPwd.substring(0, strUsernameAndPwd.indexOf(":"));
strPassWord = strUsernameAndPwd.substring(strUsernameAndPwd.indexOf(":") + 1);
}
// 截取ftp文件路径和文件名
String strFileNameAndPath = "";
if (cutedFtp.indexOf("/") != -1) {
strFileNameAndPath = cutedFtp.substring(cutedFtp.indexOf("/") + 1, cutedFtp.length());
} else {
strFileNameAndPath = "";
}
// 开始获取ftp文件路径和文件名
if (!"".equals(strIpAndPort)) {
if (strFileNameAndPath.indexOf("/") != -1) {
strRemotePath = strFileNameAndPath.substring(0, strFileNameAndPath.lastIndexOf("/"));
strFileName = strFileNameAndPath.substring(strFileNameAndPath.lastIndexOf("/") + 1,
strFileNameAndPath.length());
} else {
strFileName = strFileNameAndPath;
}
}
}
strLocalPath = PROJECT_PATH + strRelativePath + strFileName;
logger.info("file download target path: " + strLocalPath);
File file = new File(strLocalPath);
if (!file.isDirectory()) { // 目录不存在
String[] aPathSegments = strLocalPath.split("/");
String strWalkThroughPath = "/";
for (int i = 0; i < aPathSegments.length - 1; i++) {
strWalkThroughPath = strWalkThroughPath + "/" + aPathSegments[i];
file = new File(strWalkThroughPath);
if (!file.isDirectory()) {
file.mkdir();
}
}
}
boolean b = FTPUtils.downFile(strUrl, iPort, strUserName, strPassWord, strRemotePath, strFileName,
PROJECT_PATH + strRelativePath);
if (!b) {
// 下载失败
logger.info("file download error: " + strLocalPath);
return "";
} else {
logger.info("file saved: " + strLocalPath);
}
return strLocalPath;
}
public static void main(String[] args) {
try {
//FileInputStream in = new FileInputStream(new File("D:/adv.txt"));
//boolean flag = uploadFile("10.50.127.181", 21, "root", "bestvwin", "/tmp", "adv.txt", in);
//boolean flag = downFile("172.25.44.26", 21, "wacos", "wacos", "/opt/wacos/CTMSData/picture/2018/02/07",
// "20180207112330_320029.jpg", "");
//System.out.println(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
}