-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFTP API for listing files and directories
More file actions
98 lines (81 loc) · 2.92 KB
/
Copy pathFTP API for listing files and directories
File metadata and controls
98 lines (81 loc) · 2.92 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
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* An example program that demonstrates how to list files and directories
* on a FTP server using Apache Commons Net API.
* @author www.codejava.net
*/
public class FTPListDemo {
public static void main(String[] args) {
String server = "www.ftpserver.com";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
// Lists files and directories
FTPFile[] files1 = ftpClient.listFiles("/public_ftp");
printFileDetails(files1);
// uses simpler methods
String[] files2 = ftpClient.listNames();
printNames(files2);
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
} finally {
// logs out and disconnects from server
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void printFileDetails(FTPFile[] files) {
DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (FTPFile file : files) {
String details = file.getName();
if (file.isDirectory()) {
details = "[" + details + "]";
}
details += "\t\t" + file.getSize();
details += "\t\t" + dateFormater.format(file.getTimestamp().getTime());
System.out.println(details);
}
}
private static void printNames(String files[]) {
if (files != null && files.length > 0) {
for (String aFile: files) {
System.out.println(aFile);
}
}
}
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
}