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:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * FTP?./* w w  w  .j  a  v a2  s. c om*/
 * 
 * @param remotePath
 *            FTP?
 * @param fileName
 *            ???
 * @param localPath
 *            ??
 * @return
 */
public boolean ftpDownFile(String remotePath, String fileName, String localPath) {
    // ?
    boolean success = false;
    // FTPClient
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("GBK");
    try {
        int reply;
        // FTP?
        // ??ftp.connect(url)?FTP?
        ftp.connect(url, port);
        // ftp
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(remotePath);
        // 
        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();
                success = true;
            }
        }
        ftp.logout();
        // ?

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:com.claim.controller.FileTransferController.java

public void readFilesFromServer(String targetDirectory) {
    FTPClient ftpClient = new FTPClient();
    try {//w  w  w  .  ja  va2  s. c o m

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
        ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();
        FTPFile[] ftpFiles = ftpClient.listFiles();

        if (ftpFiles != null && ftpFiles.length > 0) {
            //loop thru files
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());

                //get output stream
                OutputStream output;
                //output = new FileOutputStream(FTP_REMOTE_HOME + "/" + file.getName());
                output = new FileOutputStream(file.getName());
                //get the file from the remote system
                ftpClient.retrieveFile(file.getName(), output);
                //close output stream
                output.close();

                //delete the file
                //ftpClient.deleteFile(file.getName());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(FileTransferController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:adams.core.io.lister.FtpDirectoryLister.java

/**
 * Performs the recursive search. Search goes deeper if != 0 (use -1 to
 * start with for infinite search).//w w  w . j  a va  2 s. com
 *
 * @param client   the client to use
 * @param current   the current directory
 * @param files   the files collected so far
 * @param depth   the depth indicator (searched no deeper, if 0)
 * @throws Exception   if listing fails
 */
protected void search(FTPClient client, String current, List<SortContainer> files, int depth) throws Exception {
    List<FTPFile> currFiles;
    int i;
    FTPFile entry;
    SortContainer cont;

    if (depth == 0)
        return;

    if (getDebug())
        getLogger().info("search: current=" + current + ", depth=" + depth);

    client.changeWorkingDirectory(current);
    currFiles = new ArrayList<>();
    currFiles.addAll(Arrays.asList(client.listFiles()));
    if (currFiles.size() == 0) {
        if (getDebug())
            getLogger().info("No files listed!");
        return;
    }

    for (i = 0; i < currFiles.size(); i++) {
        // do we have to stop?
        if (m_Stopped)
            break;

        entry = currFiles.get(i);

        // directory?
        if (entry.isDirectory()) {
            // ignore "." and ".."
            if (entry.getName().equals(".") || entry.getName().equals(".."))
                continue;

            // search recursively?
            if (m_Recursive)
                search(client, current + "/" + entry.getName(), files, depth - 1);

            if (m_ListDirs) {
                // does name match?
                if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName()))
                    continue;

                files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting));
            }
        } else {
            if (m_ListFiles) {
                // does name match?
                if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName()))
                    continue;

                files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting));
            }
        }
    }
}

From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java

@SuppressWarnings("fallthrough")
private int transferFiles(FTPClient ftp, File[] files, IProgressMonitor monitor, IAdaptable adaptable,
        boolean deleteTransferred) throws IOException {
    if (monitor.isCanceled())
        return -1;
    FTPFile[] oldfiles = ftp.listFiles();
    if (monitor.isCanceled())
        return -1;
    Map<String, FTPFile> names = new HashMap<String, FTPFile>();
    for (FTPFile file : oldfiles)
        names.put(file.getName(), file);
    int n = 0;/*from ww  w . j  a  v  a2  s  . co  m*/
    for (File file : files) {
        final String filename = file.getName();
        FTPFile ftpFile = names.get(filename);
        if (file.isDirectory()) {
            if (ftpFile != null) {
                if (!ftpFile.isDirectory())
                    throw new IOException(
                            NLS.bind(Messages.FtpAccount_cannot_replace_file_with_subdir, filename));
                boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename));
                if (!result)
                    throw new IOException(NLS.bind(Messages.FtpAccount_cannot_change_to_working_dir, filename));
                // System.out.println(filename + " is new directory"); //$NON-NLS-1$
            } else {
                ftp.makeDirectory(filename);
                boolean result = ftp.changeWorkingDirectory(Core.encodeUrlSegment(filename));
                if (!result)
                    throw new IOException(Messages.FtpAccount_creation_of_subdir_failed);
                // System.out.println(filename + " is new directory"); //$NON-NLS-1$
            }
            if (monitor.isCanceled())
                return -1;
            int c = transferFiles(ftp, file.listFiles(), monitor, adaptable, deleteTransferred);
            if (c < 0)
                return -1;
            n += c;
            ftp.changeToParentDirectory();
            // System.out.println("Returned to parent directory"); //$NON-NLS-1$
        } else {
            if (ftpFile != null) {
                if (ftpFile.isDirectory())
                    throw new IOException(
                            NLS.bind(Messages.FtpAccount_cannot_replace_subdir_with_file, filename));
                if (skipAll) {
                    if (deleteTransferred)
                        file.delete();
                    continue;
                }
                if (!replaceAll) {
                    if (monitor.isCanceled())
                        return -1;
                    int ret = 4;
                    IDbErrorHandler errorHandler = Core.getCore().getErrorHandler();
                    if (errorHandler != null) {
                        String[] buttons = (filecount > 1)
                                ? new String[] { Messages.FtpAccount_overwrite,
                                        Messages.FtpAccount_overwrite_all, IDialogConstants.SKIP_LABEL,
                                        Messages.FtpAccount_skip_all, IDialogConstants.CANCEL_LABEL }
                                : new String[] { Messages.FtpAccount_overwrite, IDialogConstants.SKIP_LABEL,
                                        IDialogConstants.CANCEL_LABEL };
                        ret = errorHandler.showMessageDialog(Messages.FtpAccount_file_already_exists, null,
                                NLS.bind(Messages.FtpAccount_file_exists_overwrite, filename),
                                MessageDialog.QUESTION, buttons, 0, adaptable);
                    }
                    if (filecount > 1) {
                        switch (ret) {
                        case 0:
                            break;
                        case 1:
                            replaceAll = true;
                            break;
                        case 3:
                            skipAll = true;
                            /* FALL-THROUGH */
                        case 2:
                            if (deleteTransferred)
                                file.delete();
                            continue;
                        default:
                            return -1;
                        }
                    } else {
                        switch (ret) {
                        case 0:
                            break;
                        case 1:
                            if (deleteTransferred)
                                file.delete();
                            continue;
                        default:
                            return -1;
                        }
                    }
                }
                ftp.deleteFile(Core.encodeUrlSegment(filename));
                //               System.out.println(filename + " deleted"); //$NON-NLS-1$
            }
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
                ftp.storeFile(Core.encodeUrlSegment(filename), in);
                //               System.out.println(filename + " stored"); //$NON-NLS-1$
                n++;
            } finally {
                if (deleteTransferred)
                    file.delete();
                monitor.worked(1);
            }
        }
    }
    return n;
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

/**
 * @param host FTP Host name.// w  w  w  .  j  a v a 2 s . co m
 * @param port FTP port.
 * @param user FTP User.
 * @param pswd FTP Password.
 * @param c    Context
 * @return Downloaded name file or blank list if something was going wrong.
 */
private String FTPDownloadFile(String host, Integer port, String user, String pswd, Context c) {
    String result = "";
    FTPClient mFTPClient = null;

    try {
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // Now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {

            // Login using username & password
            boolean status = mFTPClient.login(user, pswd);
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA);
            FTPFile[] fileList = mFTPClient.listFiles();
            long timestamp = 0l;
            String nameFile = "";
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) {
                    timestamp = fileList[i].getTimestamp().getTimeInMillis();
                    nameFile = fileList[i].getName();
                }
            }
            Log.d(TAG, "File da scaricare: " + nameFile);

            mFTPClient.enterLocalActiveMode();
            File folder = new File(Constants.DIR_ROBOT_IMG);
            OutputStream outputStream = null;
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }

            try {
                outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile);
                success = mFTPClient.retrieveFile(nameFile, outputStream);
            } catch (Exception e) {
                return e.getMessage();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            if (success) {
                result = nameFile;
                mFTPClient.deleteFile(nameFile);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (mFTPClient != null) {
            try {
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    return result;
}

From source file:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 */// w w  w.j a v  a  2  s  .  c  o  m
@Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000)
public void checkFiles() {
    log.info("Checking FTP files at DMI.");
    FTPClient client = new FTPClient();
    try {
        client.setDataTimeout(20 * 1000);
        client.setBufferSize(1024 * 1024);
        client.connect(hostname);
        if (client.login("anonymous", "")) {
            try {
                client.enterLocalPassiveMode();
                client.setFileType(FTP.BINARY_FILE_TYPE);
                for (ForecastConfiguration configuration : configurations) {
                    // DMI creates a Newest link once all files have been created
                    if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) {
                        if (client.getReplyCode() != 250) {
                            log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode());
                        }
                        String workingDirectory = new File(client.printWorkingDirectory()).getName();
                        String previousNewest = newestDirectories.get(configuration);
                        if (!workingDirectory.equals(previousNewest)) {
                            // a new directory for this configuration is available on the server
                            FTPFile[] listFiles = client.listFiles();
                            List<FTPFile> files = Arrays.stream(listFiles)
                                    .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches())
                                    .collect(Collectors.toList());

                            try {
                                Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory,
                                        files);
                                gridWeatherService.newFiles(localFiles, configuration);
                            } catch (IOException e) {
                                log.warn("Unable to get new weather files from DMI", e);
                            }

                            if (previousNewest != null) {
                                File previous = new File(tempDirLocation, previousNewest);
                                deleteRecursively(previous);
                            }
                            newestDirectories.put(configuration, workingDirectory);
                        }

                    } else {
                        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
                        log.error("Unable to change ftp directory to {}", configuration.getFolder());
                    }
                }
            } finally {
                try {
                    client.logout();
                } catch (IOException e) {
                    log.info("Failed to logout", e);
                }
            }
        } else {
            gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
            log.error("Unable to login to {}", hostname);
        }

    } catch (IOException e) {
        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
        log.error("Unable to update weather files from DMI", e);
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            log.info("Failed to disconnect", e);
        }
    }
    log.info("Check completed.");
}

From source file:adams.flow.source.FTPLister.java

/**
 * Executes the flow item.//  ww w .  ja va2  s  .  c  o  m
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    FTPClient client;
    FTPFile[] files;

    result = null;

    m_Queue.clear();
    client = m_Connection.getFTPClient();
    if (m_ListDirs) {
        try {
            if (m_RemoteDir.length() > 0)
                client.changeWorkingDirectory(m_RemoteDir);
            files = client.listDirectories();
            for (FTPFile file : files) {
                if (isStopped())
                    break;
                if (file == null)
                    continue;
                if (m_RegExp.isEmpty() || m_RegExp.isMatchAll() || m_RegExp.isMatch(file.getName()))
                    m_Queue.add(file.getName());
            }
        } catch (Exception e) {
            result = handleException("Failed to list directories in '" + m_RemoteDir + "': ", e);
        }
    }

    if (result == null) {
        if (m_ListFiles) {
            try {
                if (m_RemoteDir.length() > 0)
                    client.changeWorkingDirectory(m_RemoteDir);
                files = client.listFiles();
                for (FTPFile file : files) {
                    if (isStopped())
                        break;
                    if (file == null)
                        continue;
                    if (file.isDirectory())
                        continue;
                    if (m_RegExp.isEmpty() || m_RegExp.isMatchAll() || m_RegExp.isMatch(file.getName()))
                        m_Queue.add(file.getName());
                }
            } catch (Exception e) {
                result = handleException("Failed to list files in '" + m_RemoteDir + "': ", e);
            }
        }
    }

    if (isStopped())
        m_Queue.clear();

    return result;
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downIBSA() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*from  w w w .  j  av a  2s  .c om*/
        FileInputStream glnCodesCsv = new FileInputStream(Constants.DIR_IBSA + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(glnCodesCsv, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("IbsaAmiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory("data");
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        System.out.println("- Connected to server " + fs + "...");
        //get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();

        List<String> list_remote_files = Arrays.asList("Konditionen.csv", "Targeting_diff.csv", "Address.csv");
        List<String> list_local_files = Arrays.asList(Constants.FILE_CUST_IBSA, Constants.FILE_TARG_IBSA,
                Constants.FILE_MOOS_ADDR);

        if (ftpFiles != null && ftpFiles.length > 0) {
            int index = 0;
            for (String remote_file : list_remote_files) {
                OutputStream os = new FileOutputStream(Constants.DIR_IBSA + "/" + list_local_files.get(index));
                System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");

                boolean done = ftp_client.retrieveFile(remote_file, os);
                if (done)
                    System.out.println("file downloaded successfully.");
                else
                    System.out.println("error.");
                os.close();
                index++;
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downDesitin() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*ww  w.  j a  va2s .  c  o  m*/
        FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("ftp_amiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        // Set working directory
        String working_dir = "ywesee_in";
        ftp_client.changeWorkingDirectory(working_dir);
        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }
        // Get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            // ... then download all csv files
            for (FTPFile f : ftpFiles) {
                String remote_file = f.getName();
                if (remote_file.endsWith("csv")) {
                    String local_file = remote_file;
                    if (remote_file.startsWith("Kunden"))
                        local_file = Constants.FILE_CUST_DESITIN;
                    if (remote_file.startsWith("Artikel"))
                        local_file = Constants.FILE_ARTICLES_DESITIN;
                    OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file);
                    System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                    boolean done = ftp_client.retrieveFile(remote_file, os);
                    if (done)
                        System.out.println("success.");
                    else
                        System.out.println("error.");
                    os.close();
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downZurRose() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*www. jav a2s. c om*/
        FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("P_ywesee")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        String[] working_dir = { "ywesee out", "../ywesee in" };

        for (int i = 0; i < working_dir.length; ++i) {
            // Set working directory
            ftp_client.changeWorkingDirectory(working_dir[i]);
            int reply = ftp_client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp_client.disconnect();
                System.err.println("FTP server refused connection.");
                return;
            }
            // Get list of filenames
            FTPFile[] ftpFiles = ftp_client.listFiles();
            if (ftpFiles != null && ftpFiles.length > 0) {
                // ... then download all csv files
                for (FTPFile f : ftpFiles) {
                    String remote_file = f.getName();
                    if (remote_file.endsWith("csv")) {
                        String local_file = remote_file;
                        if (remote_file.startsWith("Artikelstamm"))
                            local_file = Constants.CSV_FILE_DISPO_ZR;
                        OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + local_file);
                        System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                        boolean done = ftp_client.retrieveFile(remote_file, os);
                        if (done)
                            System.out.println("success.");
                        else
                            System.out.println("error.");
                        os.close();
                    }
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}