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
| import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPBrowser {
public static void main(String[] args) {
try {
FTPClient client = new FTPClient();
connect(client, "FTPServer", "login", "password");
browse(client, "/");
disconnect(client);
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void browse(FTPClient client, String path) throws IOException {
FTPFile[] files = client.listFiles(path);
for(int i=0; i<files.length; i++)
{
if(files[i]!=null && !files[i].getName().equals(".") && !files[i].getName().equals(".."))
{
System.out.println(path + files[i].getName());
if(files[i].getType() != FTPFile.SYMBOLIC_LINK_TYPE && files[i].isDirectory())
browse(client, path + files[i].getName() + "/");
}
}
}
public static void connect(FTPClient client, String ftpServerAddress, String login, String password) throws SocketException, IOException {
//try to establish a connection with the FTP server
client.connect(ftpServerAddress);
//test the connection
if(FTPReply.isPositiveCompletion(client.getReplyCode()))
{
//try to log in (for a authenticated access)
if(login != null && !login.equals("") && password != null && !password.equals(""))
{
client.login(login, password);
if(FTPReply.isPositiveCompletion(client.getReplyCode()))
System.out.println("Connected to the FTP server '" + ftpServerAddress + "'...");
else
System.err.println("Unable to login to the FTP server '" + ftpServerAddress + "' - server reply: " + client.getReplyString());
}
}
else
System.err.println("Unable to establish a connection with the FTP server '" + ftpServerAddress + "' - server reply: " + client.getReplyString());
}
public static void disconnect(FTPClient client) throws IOException {
client.logout();
client.disconnect();
System.out.println("Disconnected from the FTP server...");
}
} |
Partager