Java中通过FTP上传和下载

Java中通过FTP上传和下载

一个JAVA实现FTP功能的代码,包括了服务器的设置模块,并包括有上传文件至FTP的通用方法、下载文件的通用方法以及删除文件、在ftp服务器上穿件文件夹、检测文件夹是否存在等,里面的有些代码对编写JAVA文件上传或许有参考价值,直接把代码贴出来了,注释写的很详细,大家可以参考参考.

1.FtpUtil

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
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import org.apache.log4j.Logger;

public class FtpUtil {
// 日志
private static final Logger log = Logger.getLogger(FtpUtil.class);
private FtpBean ftpBean = null;
private FtpClient client = null;

public FtpUtil(FtpBean ftpBean) {
super();
this.ftpBean = ftpBean;
}

/**
* 连接ftp服务
*
* @return
* @throws IOException
*/
public FtpClient openFtp() throws IOException {
log.debug("正在连接" + ftpBean.getHostName() + ",请等待.....");
if(ftpBean==null||ftpBean.getHostName()==null||"".equals(ftpBean.getHostName()))
throw new IOException("Ftp连接地址为空!!!");

client = new FtpClient(ftpBean.getHostName(), ftpBean.getDefaultport());
client.login(ftpBean.getUserName(), ftpBean.getPassword());
client.binary();
log.debug("连接主机:" + ftpBean.getHostName() + "成功!");
return client;
}

/**
*
* <p>上传文件或目录: </p>
*
* @param sourceSrc
* 上传的文件或目录
* @param targetSrc
* 上传目标目录
* @author humf
* @return void
* @version 1.0
*/
public void uploadFile(String sourceSrc, String targetSrc,String rootSrc) throws Exception {
log.debug("sourceSrc:" + sourceSrc + "<==>targetSrc:" + targetSrc+"<-->"+rootSrc);
client.cd(rootSrc);
String root = "";
File file = new File(sourceSrc);
if (!file.exists())
throw new FileNotFoundException();

if (file.isDirectory()) {
createDir(targetSrc, false);
File[] files = file.listFiles();
for (File fs : files) {
if (!fs.isDirectory()) {
uplocalFile(fs);
}
//log.debug("目录下所有文件名称【" + fs.getAbsolutePath() + "】");
}
} else {
log.debug("----===="+file.getParent());
createDir(targetSrc.substring(0,targetSrc.lastIndexOf("/")), false);
uplocalFile(file);
}
}

/**
*
* <p> 上传单个文件:</p>
*
* @param sourceSrc
* 原文件
* @param
* @author
* @return void
* @version 1.0
*/
private void uplocalFile(File file) throws FileNotFoundException, IOException {
//log.debug("上传的文件【" + file.getAbsolutePath() + "】");
RandomAccessFile source = new RandomAccessFile(file, "r");
source.seek(0);
DataOutputStream os = null;
TelnetOutputStream target = null;
int ch;
target = client.put(file.getName());
os = new DataOutputStream(target);
byte[] buf = new byte[10240];
while ((ch = source.read(buf)) != -1) {
os.write(buf,0,ch);
}


/* while (source.getFilePointer() < source.length()) {
ch = source.read();
os.write(ch);
}*/
os.close();
target.close();
source.close();
}

/**
* 关闭ftp服务
*
* @throws IOException
*/
public void closeFtp() throws IOException {
if (null != client) {
log.debug("与主机" + client.getUseFtpProxy() + "连接已断开!");
client.closeServer();

}
}

/**
* 建立FTP文件夹
*
* @param d
* @param isDeep
* @return
*/
private boolean createDir(String d, boolean isDeep) {
boolean success = true;

if (isDeep) {
try {

client.cd(d);
//log.debug("目录【" + d + "】存在!");
} catch (IOException e) {
//log.debug("目录【" + d + "】不存在,开始创建...");
client.sendServer("mkd " + d + "\r\n");
try {
client.cd(d);
client.binary();
client.readServerResponse();
} catch (IOException e1) {
e.printStackTrace();
success = false;
}
}
return success;
} else {
//log.debug("开始创建文件夹【" + d + "】...");
if (null == d && "".equals(d)) {
success = false;
}

String[] dArray = d.split("/");
for (int i = 0; i < dArray.length; i++) {
if (null == dArray[i] || "".equals(dArray[i])) {
continue;
}
//log.debug("验证子文件夹【" + dArray[i] + "】是否存在...");
StringBuilder dir = new StringBuilder();
dir.append(dArray[i]);
if (!createDir(dArray[i].toString(), true)) {
success = false;
break;
}
}

}
return success;
}

}

2.FtpBean

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
public class FtpBean {

// ftp服务器地址
private String hostName;

//ftp服务器默认端口
public static int defaultport = 21;

// 登录名
private String userName;

// 登录密码
private String password;

// 需要访问的远程目录
private String uploadDir="";

private boolean isChTimeZone;

public String getHostName() {
return hostName;
}

public void setHostName(String hostName) {
this.hostName = hostName;
}

public static int getDefaultport() {
return defaultport;
}

public static void setDefaultport(int defaultport) {
FtpBean.defaultport = defaultport;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUploadDir() {
return uploadDir;
}

public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}

public boolean isChTimeZone() {
return isChTimeZone;
}

public void setChTimeZone(boolean isChTimeZone) {
this.isChTimeZone = isChTimeZone;
}

public FtpBean(String hostName, String userName, String password) {
super();
this.hostName = hostName;
this.userName = userName;
this.password = password;

}

public FtpBean() {
super();
}


}

3.FTPclient

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
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.log4j.Logger;
import sun.net.TelnetOutputStream;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;


public class FTPclient {

private String localfilename;

private String localSource;//ftp下载后存放的本地目录

private String remotefilename;

/**
* 日志
*/
private static final Logger log = Logger.getLogger( FTPclient.class.getName() );
FtpClient ftpClient;

// server:服务器名字
// user:用户名
// password:密码
// path:服务器上的路径
public void connectServer(String ip, int port,String user
, String password,String path) {

try {

ftpClient = new FtpClient();
ftpClient.openServer(ip,port);
ftpClient.login(user, password);
log.info("ftpPaht="+ip+":" + "port:" + port +"login success!");
if (path.length() != 0) ftpClient.cd(path);
ftpClient.binary();
} catch (IOException ex) {
log.info("ftpPaht="+ip+":" + "port:" + port +"not login");
log.info(ex);
}
}

public void closeConnect() {
try {
ftpClient.closeServer();
log.info("disconnect success");
} catch (IOException ex) {
log.info("not disconnect");
log.info(ex);
}
}

public void upload() {

// this.localfilename = "D://test2//test.txt";
// this.remotefilename = "test.txt";

try {
TelnetOutputStream os = ftpClient.put(this.remotefilename);
java.io.File file_in = new java.io.File(this.localfilename);
FileInputStream is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
log.info(localfilename + "upload success");
is.close();
os.close();
} catch (IOException ex) {
log.info(localfilename + "not upload");
log.info(ex);
}
}


public void download() {

try {
TelnetInputStream is = ftpClient.get(this.remotefilename);
java.io.File file_in = new java.io.File(this.localfilename);
FileOutputStream os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
// System.out.println((char)is.read());
// System.out.println(file_in);
os.write(bytes, 0, c);
}

log.info(remotefilename + "download success");
os.close();
is.close();
} catch (IOException ex) {
log.info(remotefilename + "not download");
log.info(ex);
}
}

public void download(String remotePath,String remoteFile,String localFile) {

try {
if (remotePath.length() != 0) ftpClient.cd(remotePath);
TelnetInputStream is = ftpClient.get(remoteFile);
java.io.File file_in = new java.io.File(localFile);
FileOutputStream os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
// System.out.println((char)is.read());
// System.out.println(file_in);
os.write(bytes, 0, c);
}

log.info(remoteFile + "download success");
os.close();
is.close();
} catch (IOException ex) {
log.info(remoteFile + "not download");
log.info(ex);
}
}

public void download(String remoteFile,String localFile) {

try {
TelnetInputStream is = ftpClient.get(remoteFile);
java.io.File file_in = new java.io.File(localFile);
FileOutputStream os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
// System.out.println((char)is.read());
// System.out.println(file_in);
os.write(bytes, 0, c);
}

log.info(remoteFile + "download success");
os.close();
is.close();
} catch (IOException ex) {
log.info(remoteFile + "not download");
log.info(ex);
}
}

public void makeDirectory(String ftpdirectory) throws IOException{

try
{
char ch = ' ';
if (ftpdirectory.length() > 0)
ch = ftpdirectory.charAt(ftpdirectory.length() - 1);
for (; ch == '/' || ch == '\\'; ch = ftpdirectory.charAt(ftpdirectory.length() - 1))
ftpdirectory = ftpdirectory.substring(0, ftpdirectory.length() - 1);

int slashindex = ftpdirectory.indexOf(47);
int backslashindex = ftpdirectory.indexOf(92);
int index = slashindex;
String dirall = ftpdirectory;
if (backslashindex != -1 && (index == -1 || index > backslashindex))
index = backslashindex;
String directory = "";
while (index != -1) {
if (index > 0) {
String dir = dirall.substring(0, index);
directory = directory + "/" + dir;
ftpClient.sendServer("xmkd " + directory + "\r\n");
ftpClient.readServerResponse();
}
dirall = dirall.substring(index + 1);
slashindex = dirall.indexOf(47);
backslashindex = dirall.indexOf(92);
index = slashindex;
if (backslashindex != -1 && (index == -1 || index > backslashindex))
index = backslashindex;
}
ftpClient.sendServer("xmkd " + ftpdirectory + "\r\n");
ftpClient.readServerResponse();
}
catch(Exception e)
{
e.printStackTrace();

}
}
public static void main(String agrs[]) {

String filepath[] = { "/callcenter/index.jsp", "/callcenter/ip.txt",
"/callcenter/mainframe/image/processing_bar_2.gif",
"/callcenter/mainframe/image/logo_01.jpg" };
String localfilepath[] = { "C:\\FTP_Test\\index.jsp",
"C:\\FTP_Test\\ip.txt", "C:\\FTP_Test\\processing_bar_2.gif",
"C:\\FTP_Test\\logo_01.jpg" };

FTPclient fu = new FTPclient();
fu.connectServer("172.16.1.66",22, "web_test", "123456","/callcenter");
for(int i=0;i<filepath.length;i++){
fu.download(filepath[i],localfilepath[i]);
}

// fu.upload();
// fu.download();
fu.closeConnect();

}

public String getLocalfilename() {
return localfilename;
}

public void setLocalfilename(String localfilename) {
this.localfilename = localfilename;
}

public String getRemotefilename() {
return remotefilename;
}

public void setRemotefilename(String remotefilename) {
this.remotefilename = remotefilename;
}

public String getLocalSource() {
return localSource;
}

public void setLocalSource(String localSource) {
this.localSource = localSource;
}
}

本作品采用知识共享署名 4.0 中国大陆许可协议进行许可,欢迎转载,但转载请注明来自御前提笔小书童,并保持转载后文章内容的完整。本人保留所有版权相关权利。

本文链接:https://royalscholar.cn/2017/04/26/Java中通过FTP上传和下载/

# FTP, JAVA

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×