FTPClientUtils.java
2.89 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
package com.bsth.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
* @Description: 向FTP服务器上传文件
*
* @Version 1.0 2016-06-21 4:31:09 by 李强
*
*/
public class FTPClientUtils {
/**
* @param url FTP服务器hostname;
*
* - - - - port FTP服务器端口;
*
* - - - - username FTP登录账号;
*
* - - - - password FTP登录密码 ;
*
* - - - - path FTP服务器保存目录;
*
* - - - - filename 上传到FTP服务器上的文件名
*
* - - - - 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服务器,如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.connect(url, port);
//登录
ftp.login(username, password);
reply = ftp.getReplyCode();
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;
}
// 将本地文件上传到FTP服务器上
public void testUpLoadFromDisk(){
try {
FileInputStream in=new FileInputStream(new File("D:/test.txt"));
boolean flag = uploadFile("192.168.168.101", 21, "testftpservice", "123", "C:/ftptest", "test.txt", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 在FTP服务器上生成一个文件,并将一个字符串写入到该文件中
public void testUpLoadFromString(){
try {
String str = "test ftp "+ "\r\n"+ "ccccc dddd";
InputStream input = new ByteArrayInputStream(str.getBytes("utf-8"));
boolean flag = uploadFile("192.168.168.101", 21, "testftpservice", "123", "C:/ftptest", "test.txt", input);
System.out.println(flag);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}