Example usage for org.apache.commons.net.ftp FTPClient listFiles

List of usage examples for org.apache.commons.net.ftp FTPClient listFiles

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient listFiles.

Prototype

public FTPFile[] listFiles() throws IOException 

Source Link

Document

Using the default system autodetect mechanism, obtain a list of file information for the current working directory.

Usage

From source file:Main.java

public static void main(String[] args) {
    FTPClient client = new FTPClient();

    client.connect("ftp.domain.com");
    client.login("admin", "secret");

    String[] names = client.listNames();
    for (String name : names) {
        System.out.println("Name = " + name);
    }// w  ww .j ava  2  s  .  c o  m

    FTPFile[] ftpFiles = client.listFiles();
    for (FTPFile ftpFile : ftpFiles) {
        // Check if FTPFile is a regular file
        if (ftpFile.getType() == FTPFile.FILE_TYPE) {
            System.out.println("FTPFile: " + ftpFile.getName() + "; "
                    + FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
        }
    }
    client.logout();
    client.disconnect();
}

From source file:luisjosediez.Ejercicio2.java

/**
 * @param args the command line arguments
 *//*  ww  w .  ja  v  a 2 s.  c  om*/
public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Introduce la direccin de un servidor ftp: ");
    FTPClient cliente = new FTPClient();
    String servFTP = cadena();
    String clave = "";
    System.out.println("Introduce usuario (vaco para conexin annima): ");
    String usuario = cadena();
    String opcion;
    if (usuario.equals("")) {
        clave = "";
    } else {
        System.out.println("Introduce contrasea: ");
        clave = cadena();
    }
    try {
        cliente.setPassiveNatWorkaround(false);
        cliente.connect(servFTP, 21);
        boolean login = cliente.login(usuario, clave);
        if (login) {
            System.out.println("Conexin ok");
        } else {
            System.out.println("Login incorrecto");
            cliente.disconnect();
            System.exit(1);
        }
        do {

            System.out.println("Orden [exit para salir]: ");
            opcion = cadena();
            if (opcion.equals("ls")) {
                FTPFile[] files = cliente.listFiles();
                String tipos[] = { "Fichero", "Directorio", "Enlace" };
                for (int i = 0; i < files.length; i++) {
                    System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]);
                }
            } else if (opcion.startsWith("cd ")) {
                try {
                    cliente.changeWorkingDirectory(opcion.substring(3));
                } catch (IOException e) {
                }
            } else if (opcion.equals("help")) {
                System.out.println(
                        "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'.");
            } else if (opcion.startsWith("help ")) {
                if (opcion.endsWith(" get")) {
                    System.out.println(
                            "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'.");
                } else if (opcion.endsWith(" ls")) {
                    System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'.");
                } else if (opcion.endsWith(" cd")) {
                    System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'.");
                } else if (opcion.endsWith(" put")) {
                    System.out.println(
                            "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'.");
                }
            } else if (opcion.startsWith("get ")) {
                try {
                    System.out.println("Indique la carpeta de descarga: ");
                    try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) {
                        cliente.retrieveFile(opcion.substring(4), fos);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                }
            } else if (opcion.startsWith("put ")) {
                try {
                    try {

                        System.out.println(opcion.substring(4));

                        File local = new File(opcion.substring(4));

                        System.out.println(local.getName());

                        InputStream is = new FileInputStream(opcion.substring(4));

                        OutputStream os = cliente.storeFileStream(local.getName());

                        byte[] bytesIn = new byte[4096];

                        int read = 0;

                        while ((read = is.read(bytesIn)) != -1) {

                            os.write(bytesIn, 0, read);

                        }

                        is.close();
                        os.close();

                        boolean completed = cliente.completePendingCommand();

                        if (completed) {
                            System.out.println("The file is uploaded successfully.");
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                }
            }

        } while (!(opcion.equals("exit")));

        boolean logout = cliente.logout();
        if (logout)
            System.out.println("Logout...");
        else
            System.out.println("Logout incorrecto");

        cliente.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.axelor.apps.tool.net.MyFtp.java

public static void getDataFiles(String server, String username, String password, String folder,
        String destinationFolder, Calendar start, Calendar end) {

    try {/* w  ww .  j  ava 2s  . c o  m*/

        // Connect and logon to FTP Server
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        ftp.login(username, password);

        // List the files in the directory
        ftp.changeWorkingDirectory(folder);
        FTPFile[] files = ftp.listFiles();

        for (int i = 0; i < files.length; i++) {

            Date fileDate = files[i].getTimestamp().getTime();
            if (fileDate.compareTo(start.getTime()) >= 0 && fileDate.compareTo(end.getTime()) <= 0) {

                // Download a file from the FTP Server
                File file = new File(destinationFolder + File.separator + files[i].getName());
                FileOutputStream fos = new FileOutputStream(file);
                ftp.retrieveFile(files[i].getName(), fos);
                fos.close();
                file.setLastModified(fileDate.getTime());
            }
        }

        // Logout from the FTP Server and disconnect
        ftp.logout();
        ftp.disconnect();

    } catch (Exception e) {

        LOG.error(e.getMessage());

    }
}

From source file:eu.ggnet.dwoss.misc.op.listings.FtpTransfer.java

private static void deleteFilesByType(FTPClient ftp, Collection<String> fileTypesToDelete) throws IOException {
    if (fileTypesToDelete == null || fileTypesToDelete.isEmpty())
        return;/*  w  w w  . ja  v a 2 s  .  c  om*/
    FTPFile[] existingFiles = ftp.listFiles();
    if (existingFiles == null || existingFiles.length == 0)
        return;
    for (String type : fileTypesToDelete) {
        for (FTPFile ftpFile : existingFiles) {
            if (ftpFile == null)
                continue;
            if (ftpFile.getName().toLowerCase().endsWith(type)) {
                if (!ftp.deleteFile(ftpFile.getName())) {
                    throw new IOException("Could not delete " + ftpFile.getName());
                }
            }
        }
    }
}

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static List<String> listSequentialDatasets(String pdsName, Configuration conf) throws IOException {
    List<String> datasets = new ArrayList<String>();
    FTPClient ftp = null;
    try {/*  www  .  j a va2 s  .  c om*/
        ftp = getFTPConnection(conf);
        if (ftp != null) {
            ftp.changeWorkingDirectory("'" + pdsName + "'");
            FTPFile[] ftpFiles = ftp.listFiles();
            for (FTPFile f : ftpFiles) {
                if (f.getType() == FTPFile.FILE_TYPE) {
                    datasets.add(f.getName());
                }
            }
        }
    } catch (IOException ioe) {
        throw new IOException("Could not list datasets from " + pdsName + ":" + ioe.toString());
    } finally {
        if (ftp != null) {
            closeFTPConnection(ftp);
        }
    }
    return datasets;
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API to download files from an arbitrary directory hierarchy on the remote ftp server
 * /*from w w w  . ja va2 s . c  om*/
 * @param client {@link FTPClient}
 * @param ftpDirectory{{@link String} the directory tree only delimited with / chars. No file name!
 * @param destDirectoryPath {@link String} the path where file will be downloaded.
 * @throws Exception
 */
public static void retrieveFiles(final FTPClient client, final String ftpDirectory,
        final String destDirectoryPath) throws IOException {
    boolean dirExists = true;
    String[] directories = ftpDirectory.split(DIRECTORY_SEPARATOR);
    for (String dir : directories) {
        if (!dir.isEmpty()) {
            if (dirExists) {
                dirExists = client.changeWorkingDirectory(dir);
            }
        }
    }
    FTPFile[] fileList = client.listFiles();
    if (fileList != null && fileList.length > 0) {
        String outputFilePath;
        FileOutputStream fileOutputStream;
        for (FTPFile file : fileList) {
            outputFilePath = EphesoftStringUtil.concatenate(destDirectoryPath, File.separator, file.getName());
            fileOutputStream = new FileOutputStream(outputFilePath);
            client.retrieveFile(file.getName(), fileOutputStream);
            fileOutputStream.close();
        }
    }
}

From source file:de.l3s.dlg.ncbikraken.ftp.NcbiFTPClient.java

public static void getMedline(MedlineFileType type) {
    FileOutputStream out = null;//from   w w  w  . j  a va 2 s.  c o m
    FTPClient ftp = new FTPClient();
    try {
        // Connection String
        LOGGER.info("Connecting to FTP server " + SERVER_NAME);
        ftp.connect(SERVER_NAME);
        ftp.login("anonymous", "");
        ftp.cwd(BASELINE_PATH);
        ftp.cwd(type.getServerPath());

        try {
            ftp.pasv();
        } catch (IOException e) {
            LOGGER.error(
                    "Can not access the passive mode. Maybe a problem with your (Windows) firewall. Just try to run as administrator: \nnetsh advfirewall set global StatefulFTP disable");
            return;
        }

        for (FTPFile file : ftp.listFiles()) {
            if (file.isFile()) {
                File meshF = new File(file.getName());
                LOGGER.debug("Downloading file: " + SERVER_NAME + ":" + BASELINE_PATH + "/"
                        + type.getServerPath() + "/" + meshF.getName());
                out = new FileOutputStream(Configuration.INSTANCE.getMedlineDir() + File.separator + meshF);
                ftp.retrieveFile(meshF.getName(), out);
                out.flush();
                out.close();
            }
        }

    } catch (IOException ioe) {
        LOGGER.error(ioe.getMessage());

    } finally {
        IOUtils.closeQuietly(out);
        try {
            ftp.disconnect();
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }

}

From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java

/**
 * Description: FTP?//  ww w  . j  a va  2s. c  o  m
 *
 * @Version1.0
 * @param url FTP?hostname
 * @param port FTP??
 * @param username FTP?
 * @param password FTP?
 * @param remotePath FTP?
 * @param fileName ???
 * @param localPath ??
 * @return
 */
public static boolean downloadFile(String url, int port, String username, String password, String remotePath,
        String fileName, String localPath) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        // FTP?
        if (port > -1) {
            ftp.connect(url, port);
        } else {
            ftp.connect(url);
        }
        ftp.login(username, password);//
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(remotePath);//FTP?
        FTPFile[] fs = ftp.listFiles();
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                File localFile = new File(localPath + "/" + ff.getName());
                OutputStream is = new FileOutputStream(localFile);
                ftp.retrieveFile(ff.getName(), is);
                is.close();
            }
        }

        ftp.logout();
        success = true;
    } catch (IOException e) {
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
            }
        }
    }
    return success;
}

From source file:joshuatee.wx.UtilityFTP.java

public static String[] GetNidsArr(Context c, String url, String path, String frame_cnt_str) {

    int frame_cnt = Integer.parseInt(frame_cnt_str);
    String[] nids_arr = new String[frame_cnt];

    try {/* w  w  w.j  a  va 2 s.c  o  m*/
        FTPClient ftp = new FTPClient();

        //String user = "ftp";
        //String pass = "anonymous";

        ftp.connect(url);

        if (!ftp.login("ftp", "anonymous")) {
            ftp.logout();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        ftp.enterLocalPassiveMode();
        ftp.changeWorkingDirectory(path);
        //reply = ftp.getReplyCode();

        FTPFile[] ftpFiles = ftp.listFiles();

        //get newest .xml file name from ftp server
        java.util.Date lastMod = ftpFiles[0].getTimestamp().getTime();
        FTPFile choice = ftpFiles[0];

        for (FTPFile file : ftpFiles) {
            if (file.getTimestamp().getTime().after(lastMod) && !file.getName().equals("sn.last")) {
                choice = file;
                lastMod = file.getTimestamp().getTime();
            }
        }

        int seq = Integer.parseInt(choice.getName().replace("sn.", "")); // was ALl
        int j = 0;
        int k = seq - frame_cnt + 1;
        for (j = 0; j < frame_cnt; j++) {
            // files range from 0000 to 0250, if num is negative add 251
            int tmp_k = k;

            if (tmp_k < 0)
                tmp_k = tmp_k + 251;

            nids_arr[j] = "sn." + String.format("%4s", Integer.toString(tmp_k)).replace(' ', '0');
            k++;
        }

        FileOutputStream fos;
        for (j = 0; j < frame_cnt; j++) {
            fos = c.openFileOutput(nids_arr[j], Context.MODE_PRIVATE);
            ftp.retrieveFile(nids_arr[j], fos);
            fos.close();
        }

        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return nids_arr;

}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void setInitialLocationType(RepositoryLocation location) {

    FTPClient client = RepositoryClientUtil.connect(location, false);

    if (client != null) {

        String tempDir = "";

        try {/* www.  j  a  v  a2  s. co m*/
            String eclipseInstallationDirectory = Platform.getInstallLocation().getURL().getPath();
            tempDir = RepositoryClientUtil.createFolder(eclipseInstallationDirectory + "tmp", 0);

            FTPFile[] files = client.listFiles();

            if (files.length > 0) {
                String fileName = files[0].getName();
                String destination = tempDir + "/" + fileName;
                FileOutputStream fos = new FileOutputStream(destination);
                client.retrieveFile(fileName, fos);
                fos.close();

                extractZipFile(tempDir, fileName);

                Document doc = getDocument(tempDir + "/rasset.xml");
                if (doc != null) {
                    Node ntype = doc.getElementsByTagName("type").item(0);
                    String type = ntype.getAttributes().getNamedItem("value").getNodeValue();
                    if (type != null) {
                        if (isTechnicalFragment(type)) {
                            location.setType("Technical");
                        } else {
                            location.setType("Conceptual");
                        }
                    }
                }
            } else {
                location.setType("Empty");
            }
        } catch (Exception e) {

        } finally {
            RepositoryClientUtil.disconnect(client);
            if (location.getType().equals("")) {
                location.setType("Empty");
            }
            if (!tempDir.equals("")) {
                RepositoryClientUtil.removeFolder(new File(tempDir));
            }
        }
    }
}