3 import java.io.BufferedOutputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.net.SocketException;
10 import org.apache.commons.net.ftp.FTPClient;
11 import org.apache.commons.net.ftp.FTPFile;
13 public class FtpClient
16 public static boolean authenticateUser(FTPClient ftpClient,
17 String username, String password)
19 boolean loggedIn = false;
23 loggedIn = ftpClient.login(username, password);
24 } catch (IOException e)
28 disconectFTP(ftpClient);
33 public static FTPClient getFtpClient(String serverHost)
35 FTPClient ftpClient = new FTPClient();
38 ftpClient.connect(serverHost);
39 } catch (SocketException e)
42 } catch (IOException e)
49 public static void disconectFTP(FTPClient ftpClient)
53 if (ftpClient.isConnected())
56 ftpClient.disconnect();
58 } catch (IOException e)
64 public static void listDirectory(FTPClient ftpClient, String parentDir,
65 String currentDir, int level) throws IOException
67 String dirToList = parentDir;
68 if (!currentDir.equals(""))
70 dirToList += "/" + currentDir;
72 FTPFile[] subFiles = ftpClient.listFiles(dirToList);
73 if (subFiles != null && subFiles.length > 0)
75 for (FTPFile aFile : subFiles)
77 String currentFileName = aFile.getName();
78 if (currentFileName.equals(".") || currentFileName.equals(".."))
80 // skip parent directory and directory itself
83 for (int i = 0; i < level; i++)
85 System.out.print("\t");
87 if (aFile.isDirectory())
89 System.out.println("[" + currentFileName + "]");
90 listDirectory(ftpClient, dirToList, currentFileName, level + 1);
94 System.out.println(currentFileName);
100 public static boolean downloadFile(FTPClient client, String remoteFile,
103 boolean success = false;
104 File downloadFile = new File(local);
105 OutputStream outputStream = null;
108 outputStream = new BufferedOutputStream(new FileOutputStream(
111 success = client.retrieveFile(remoteFile, outputStream);
112 } catch (IOException e)
119 if (outputStream != null)
121 outputStream.close();
123 } catch (IOException e)
130 System.out.println(remoteFile + " has been downloaded successfully.");