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(String pathname) throws IOException 

Source Link

Document

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

Usage

From source file:madkitgroupextension.export.Export.java

private static void sendToWebSite() throws IOException {
    System.out.println("Enter your password :");
    byte b[] = new byte[100];
    int l = System.in.read(b);
    String pwd = new String(b, 0, l);

    boolean reconnect = true;
    long time = System.currentTimeMillis();
    File current_file_transfert = null;
    File current_directory_transfert = null;

    while (reconnect) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(FTPURL, 21);/*from   w  ww.j  av  a 2 s  .  c  o m*/
        try {
            if (ftpClient.isConnected()) {
                System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !");
                if (ftpClient.login(FTPLOGIN, pwd)) {
                    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                    System.out.println("Logged as " + FTPLOGIN + " !");
                    System.out.print("Updating...");

                    FTPFile files[] = ftpClient.listFiles("");
                    FTPFile downloadroot = null;
                    FTPFile docroot = null;

                    for (FTPFile f : files) {
                        if (f.getName().equals("downloads")) {
                            downloadroot = f;
                            if (docroot != null)
                                break;
                        }
                        if (f.getName().equals("doc")) {
                            docroot = f;
                            if (downloadroot != null)
                                break;
                        }
                    }
                    if (downloadroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("downloads")) {
                            System.err.println("Impossible to create directory: downloads");
                        }
                    }
                    if (docroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("doc")) {
                            System.err.println("Impossible to create directory: doc");
                        }
                    }

                    updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert,
                            current_directory_transfert);
                    updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert,
                            current_directory_transfert);
                    reconnect = false;

                    System.out.println("[OK]");
                    if (ftpClient.logout()) {
                        System.out.println("Logged out from " + FTPLOGIN + " succesfull !");
                    } else
                        System.err.println("Logged out from " + FTPLOGIN + " FAILED !");
                } else
                    System.err.println("Impossible to log as " + FTPLOGIN + " !");

                ftpClient.disconnect();
                System.out.println("Disconnected from " + FTPURL + " !");
            } else {
                System.err.println("Impossible to get a connection to the server " + FTPURL + " !");
            }
            reconnect = false;
        } catch (TransfertException e) {
            if (System.currentTimeMillis() - time > 30000) {
                System.err.println("A problem occured during the transfert...");
                System.out.println("Reconnection in progress...");
                try {
                    ftpClient.disconnect();
                } catch (Exception e2) {
                }
                current_file_transfert = e.current_file_transfert;
                current_directory_transfert = e.current_directory_transfert;
                time = System.currentTimeMillis();
            } else {
                System.err.println("A problem occured during the transfert. Transfert aborded.");
                throw e.original_exception;
            }
        }
    }
}

From source file:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java

private FTPFile getFile() {
    final FTPClient connection = connect();
    FTPFile[] files;/*from  w  w  w .  j av a2s .c o m*/
    try {
        files = connection.listFiles(url.getPath());
    } catch (final IOException e) {
        throw new SourceException(e);
    }
    if (files.length == 0) {
        throw new SourceException(String.format("Source file \"%s\" does not exist!", url));
    }
    disconnect(connection);
    return files[0];
}

From source file:ftp.search.Index.java

private void insertFiles(String ftp, String path, Statement stmt, FTPClient ftpClient)
        throws IOException, SQLException {

    FTPFile[] files = ftpClient.listFiles(path);

    for (FTPFile file : files) {
        String details = file.getName();
        String details2 = details.replace("'", "''");
        String path2 = ftp + path;
        String path3 = path2.replace("'", "''");
        int isDir = 0;
        if (file.isDirectory()) {
            isDir = 1;/*www  .  ja  v  a  2  s  .c  o  m*/
        }
        String query = "INSERT INTO fileindex (FileName,path,Folder) VALUES ('" + details2 + "' , '" + path3
                + "' , " + isDir + ")";

        System.out.println(query);
        stmt.executeUpdate(query);
        if (isDir == 1) {
            if (!path.contains("Games") && !(path.contains("College")) && !(path.contains("Cricket"))
                    && !(path.contains("GeekHaven")) && !(path.contains("Windows")) && !(path.contains("Win"))
                    && !(path.contains("Linux")) && !path.contains("INDEM") && !(path.contains("Telugu"))) {
                insertFiles(ftp, path + details + "/", stmt, ftpClient);
            }
        }
    }

}

From source file:com.discursive.jccook.net.FTPExample.java

private void secondExample() throws SocketException, IOException {
    FTPClient client = new FTPClient();
    client.connect("ftp.ibiblio.org");
    client.login("anonymous", "");

    String remoteDir = "/pub/mirrors/apache/jakarta/ecs/binaries";

    FTPFile[] remoteFiles = client.listFiles(remoteDir);

    System.out.println("Files in " + remoteDir);

    for (int i = 0; i < remoteFiles.length; i++) {
        String name = remoteFiles[i].getName();
        long length = remoteFiles[i].getSize();
        String readableLength = FileUtils.byteCountToDisplaySize(length);

        System.out.println(name + ":\t\t" + readableLength);
    }//  w  ww .  j  av  a  2 s.co  m

    client.disconnect();
}

From source file:com.google.android.exoplayer.upstream.FtpDataSource.java

private long getFileSize(FTPClient ftp, String filePath) throws IOException {
    long fileSize = 0;
    FTPFile[] files = ftp.listFiles(filePath);
    if (files.length == 1 && files[0].isFile()) {
        fileSize = files[0].getSize();/* w  w  w.j av  a  2s  . co m*/
    }
    return fileSize;
}

From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java

public synchronized static boolean Upload(String server, String username, String password, String directory,
        int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream,
        String fileName) {//from   ww  w .  j ava2 s . c o m
    FTPClient client = null;

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        tracer.error("Could not create FTP Client", e);
        return false;
    }

    try {
        tracer.debug("Connecting to FTP");
        client.connect(server, port);
        showServerReply(client);

        tracer.debug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();
            showServerReply(client);

            tracer.debug("Uploading file to FTP server " + server);

            tracer.debug("Checking for FTP directory " + directory);
            FTPFile[] existingDirectory = client.listFiles(directory);
            showServerReply(client);

            if (existingDirectory.length <= 0) {
                tracer.debug("Attempting to create FTP directory " + directory);
                //client.makeDirectory(directory);
                ftpCreateDirectoryTree(client, directory);
                showServerReply(client);

            }

            client.changeWorkingDirectory(directory);
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            showServerReply(client);
            if (result) {
                tracer.debug("Successfully FTPd file " + fileName);
            } else {
                tracer.debug("Failed to FTP file " + fileName);
                return false;
            }

        } else {
            tracer.debug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        tracer.error("Could not connect or upload to FTP server.", e);
        return false;
    } finally {
        try {
            tracer.debug("Logging out of FTP server");
            client.logout();
            showServerReply(client);

            tracer.debug("Disconnecting from FTP server");
            client.disconnect();
            showServerReply(client);
        } catch (Exception e) {
            tracer.error("Could not logout or disconnect", e);
            return false;
        }
    }

    return true;
}

From source file:gtu._work.ui.ObnfCheckPDFErrorUI.java

private void checkBtnActionPerformed() {
    try {//from ww w .  j av a2 s  .co  m
        for (FtpSite ftpSite : FtpSite.values()) {
            FtpUtil ftpUtil = new FtpUtil();
            ftpUtil.connect(ftpSite.ip, ftpSite.port, ftpSite.userId, ftpSite.password, false);
            FTPClient ftp = ftpUtil.getFtp();
            logArea.append("?" + ftpSite.label + "\n");
            ftp.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftp.listFiles(ftpSite.path1);
            logArea.append("-->" + ftpSite.path1 + "\n");
            for (int i = 0; i < ((ftpFiles == null) ? 0 : ftpFiles.length); i++) {
                FTPFile ftpFile = ftpFiles[i];
                if (ftpFile.isDirectory()) {
                    String p = ftpSite.path1 + "/" + ftpFile.getName() + "/" + ftpSite.path2 + "/";
                    logArea.append("-->" + p + "\n");
                    List<FtpFileInfo> fileList = new ArrayList<FtpFileInfo>();
                    ftpUtil.scanFindFile(p, ".*", fileList, ftp);
                    for (FtpFileInfo f : fileList) {
                        logArea.append("-->" + f.getAbsolutePath() + "--" + f.getSize() + "\n");
                        if (!f.isDirectory() && f.getSize() == 0) {
                            logArea.append("##" + ftpSite.label + "\t" + f.getAbsolutePath() + "\n");
                        }
                    }
                }
            }

            ftpUtil.disconnect();
            logArea.append("?:" + ftpSite.label);
        }

        JCommonUtil._jOptionPane_showMessageDialog_info("!");
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:net.audumla.climate.bom.BOMDataLoader.java

public FTPFile getFTPFile(String host, String location) throws IOException {
    FTPClient ftp = getFTPClient(host);
    try {//from w  w  w .j  av a2 s. c  om
        synchronized (ftp) {
            FTPFile[] files = ftp.listFiles(location);
            if (files.length > 0) {
                return files[0];
            } else {
                return null;
            }
        }
    } catch (IOException e) {
        try {
            ftp.logout();
            ftp.disconnect();
        } catch (Exception ex) {
            LOG.error("Failure to close connection", ex);
        }
        throw new UnsupportedOperationException(
                "Error locating File " + host + location + " FTP Code -> " + ftp.getReplyCode(), e);
    } finally {
        /*            if (!ftp.completePendingCommand()) {
        ftp.logout();
        ftp.disconnect();
                    }
                    ftp.disconnect();
        */
    }
}

From source file:com.globalsight.smartbox.util.FtpHelper.java

/**
 * Gets File Array in FTP Server by FTP Directory.
 * /*from  w  ww .  ja  v  a2  s.co m*/
 * @param directory
 *            FTP Directory
 */
public FTPFile[] ftpFileList(String p_directory) {
    FTPFile[] result = {};
    FTPClient ftpClient = getFtpClient();
    if (ftpClient != null && ftpClient.isConnected()) {
        try {
            result = ftpClient.listFiles(p_directory);
        } catch (IOException e) {
            String message = "Ftp get name list error.";
            LogUtil.fail(message, e);
        } finally {
            closeFtpClient(ftpClient);
        }
    }

    return result;
}

From source file:com.alexkasko.netty.ftp.FtpServerTest.java

@Test
public void test() throws IOException, InterruptedException {
    final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate(
            new ConsoleReceiver());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*from   www.  j  a v  a2  s.  c  o m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast("decoder", new CrlfStringDecoder());
                    pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate));
                }

            });
    b.localAddress(2121).bind();
    FTPClient client = new FTPClient();
    //        https://issues.apache.org/jira/browse/NET-493

    client.setBufferSize(0);
    client.connect("127.0.0.1", 2121);
    assertEquals(230, client.user("anonymous"));

    // active
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    assertEquals("/", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.listFiles("/foo").length == 0);
    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    //  assertTrue(client.deleteFile("baz"));

    // passive
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    client.enterLocalPassiveMode();
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());

    //TODO make a virtual filesystem that would work with directory
    //assertTrue(client.listFiles("/foo").length==1);

    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    // client.deleteFile("baz");

    assertEquals(221, client.quit());
    try {
        client.noop();
        fail("Should throw exception");
    } catch (IOException e) {
        //expected;
    }

}