Example usage for org.apache.commons.net.ftp FTPFile getName

List of usage examples for org.apache.commons.net.ftp FTPFile getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Return the name of the file.

Usage

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

private List<FileInfo> getListing(final String path, final int depth, final int maxResults) throws IOException {
    final List<FileInfo> listing = new ArrayList<>();
    if (maxResults < 1) {
        return listing;
    }/*  w  ww  .  j av a  2  s . co  m*/

    if (depth >= 100) {
        logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth
                + " to avoid memory issues");
        return listing;
    }

    final boolean ignoreDottedFiles = ctx.getProperty(FileTransferV2.IGNORE_DOTTED_FILES).asBoolean();
    final boolean recurse = ctx.getProperty(FileTransferV2.RECURSIVE_SEARCH).asBoolean();
    final String fileFilterRegex = ctx.getProperty(FileTransferV2.FILE_FILTER_REGEX).getValue();
    final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex);
    final String pathFilterRegex = ctx.getProperty(FileTransferV2.PATH_FILTER_REGEX).getValue();
    final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex);
    final String remotePath = ctx.getProperty(FileTransferV2.REMOTE_PATH).evaluateAttributeExpressions()
            .getValue();

    // check if this directory path matches the PATH_FILTER_REGEX
    boolean pathFilterMatches = true;
    if (pathPattern != null) {
        Path reldir = path == null ? Paths.get(".") : Paths.get(path);
        if (remotePath != null) {
            reldir = Paths.get(remotePath).relativize(reldir);
        }
        if (reldir != null && !reldir.toString().isEmpty()) {
            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                pathFilterMatches = false;
            }
        }
    }

    final FTPClient client = getClient(null);

    int count = 0;
    final FTPFile[] files;

    if (path == null || path.trim().isEmpty()) {
        files = client.listFiles(".");
    } else {
        files = client.listFiles(path);
    }
    if (files.length == 0 && path != null && !path.trim().isEmpty()) {
        // throw exception if directory doesn't exist
        final boolean cdSuccessful = setWorkingDirectory(path);
        if (!cdSuccessful) {
            throw new IOException("Cannot list files for non-existent directory " + path);
        }
    }

    for (final FTPFile file : files) {
        final String filename = file.getName();
        if (filename.equals(".") || filename.equals("..")) {
            continue;
        }

        if (ignoreDottedFiles && filename.startsWith(".")) {
            continue;
        }

        final File newFullPath = new File(path, filename);
        final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

        if (recurse && file.isDirectory()) {
            try {
                listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count));
            } catch (final IOException e) {
                logger.error(
                        "Unable to get listing from " + newFullForwardPath + "; skipping this subdirectory");
            }
        }

        // if is not a directory and is not a link and it matches
        // FILE_FILTER_REGEX - then let's add it
        if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) {
            if (pattern == null || pattern.matcher(filename).matches()) {
                listing.add(newFileInfo(file, path));
                count++;
            }
        }

        if (count >= maxResults) {
            break;
        }
    }

    return listing;
}

From source file:com.myJava.file.driver.remote.ftp.FTPProxy.java

/**
 * Filters the "." and ".." directories 
 *//*from  www .j  ava 2 s  . c o m*/
private boolean acceptListedFile(FTPFile file) {
    if (file == null || file.getName() == null) {
        return false;
    }

    String name = file.getName().trim().toLowerCase();
    return (!(name.endsWith("/..") || name.endsWith("\\..") || name.endsWith("/.") || name.endsWith("\\.")
            || name.equals("..") || name.equals(".")));
}

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

/**
 * Executes the flow item./*  w ww.jav  a 2s  . 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.clickha.nifi.processors.util.FTPTransferV2.java

private FileInfo newFileInfo(final FTPFile file, String path) {
    if (file == null) {
        return null;
    }//from  w w  w.  j a  va 2 s  .co  m
    final File newFullPath = new File(path, file.getName());
    final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");
    StringBuilder perms = new StringBuilder();
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION) ? "r" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION) ? "w" : "-");
    perms.append(file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION) ? "x" : "-");

    FileInfo.Builder builder = new FileInfo.Builder().filename(file.getName())
            .fullPathFileName(newFullForwardPath).directory(file.isDirectory()).size(file.getSize())
            .lastModifiedTime(file.getTimestamp().getTimeInMillis()).permissions(perms.toString())
            .owner(file.getUser()).group(file.getGroup());
    return builder.build();
}

From source file:ch.cyberduck.core.ftp.parser.UnixFTPEntryParserTest.java

@Test
public void testParseFTPEntryExpected() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    parsed = parser/*from  w  ww  .  j a v a 2s  .  com*/
            .parseFTPEntry("drw-rw-rw-   1 user      ftp             0  Mar 11 20:56 ADMIN_Documentation");
    assertNotNull(parsed);
    assertEquals(parsed.getType(), FTPFile.DIRECTORY_TYPE);
    assertEquals("user", parsed.getUser());
    assertEquals("ftp", parsed.getGroup());
    assertEquals("ADMIN_Documentation", parsed.getName());

    parsed = parser.parseFTPEntry("drwxr--r--   1 user     group          0 Feb 14 18:14 Downloads");
    assertNotNull(parsed);
    assertEquals("Downloads", parsed.getName());
}

From source file:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java

public LinkedList<AZoFTPFile> discoverRemoteFiles(String root, boolean includeDirs) throws IOException {
    LinkedList<AZoFTPFile> retval = new LinkedList();
    for (FTPFile f : ftpclient.listFiles(root)) {

        AZoFTPFile af = new AZoFTPFile(f, root);
        if (f.isFile() && isPicture(af) && !retval.contains(af)) {
            retval.add(af);//  w  w  w. j a v a2 s.c om
        }
        if (f.isDirectory()) {
            if (includeDirs) {
                retval.add(af);
            }

            retval.addAll(discoverRemoteFiles(root + f.getName() + "/", includeDirs));
        }
    }
    return retval;

}

From source file:net.sf.jfilesync.plugins.net.items.TCommonsFTP_plugin.java

protected TFileProperties extractFileProperties(FTPFile file, FTPFile[] filesInDir) throws IOException {
    TFileProperties prop = new TFileProperties();

    prop.setFileName(file.getName());

    final String cwd = ftpClient.printWorkingDirectory();
    String fname = null;// w w w.  j  a  v a 2s .  com
    if (cwd.endsWith("/")) {
        fname = cwd + file.getName();
    } else {
        fname = cwd + "/" + file.getName();
    }
    prop.setAbsoluteFileName(fname);

    if (file.getName().startsWith(".")) {
        prop.setHiddenFlag(true);
    }

    // There is a little problem with ftp.getSize(), because it's sometimes
    // 0
    prop.setFileSize(new BigInteger(Long.toString(file.getSize())));
    // System.out.println(file.getName() + " , " + file.getTimestamp());
    prop.setFileModTime(file.getTimestamp().getTimeInMillis());
    // System.out.println("file: " + fname);
    // System.out.println("isDirectory: " + file.isDirectory());
    prop.setDirectoryFlag(file.isDirectory());
    prop.setLinkFlag(file.isSymbolicLink());

    int permissions = 0;

    permissions |= file.isDirectory() ? FilePermissions.S_IFDIR : 0;
    permissions |= file.isSymbolicLink() ? FilePermissions.S_IFLNK : 0;

    permissions |= file.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION) ? FilePermissions.S_IRUSR
            : 0;
    permissions |= file.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION) ? FilePermissions.S_IWUSR
            : 0;
    permissions |= file.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) ? FilePermissions.S_IXUSR
            : 0;
    permissions |= file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION) ? FilePermissions.S_IRGRP
            : 0;
    permissions |= file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION) ? FilePermissions.S_IWGRP
            : 0;
    permissions |= file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)
            ? FilePermissions.S_IXGRP
            : 0;
    permissions |= file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION) ? FilePermissions.S_IROTH
            : 0;
    permissions |= file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION) ? FilePermissions.S_IWOTH
            : 0;
    permissions |= file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)
            ? FilePermissions.S_IXOTH
            : 0;

    final TFileAttributes attr = new TFileAttributes();
    attr.setPermissions(permissions);
    prop.setAttributes(attr);

    /*
     * what needs to be done is implement caching of directories which have
     * to be listed for link detection implement recursive link detection
     * for links to links SaHu July 2006
     */

    /*
     * if( file.isSymbolicLink() ) { System.out.println("link target : " +
     * file.getLink()); }
     */

    // if( file.isSymbolicLink() ) {
    // // check if link points to dir
    // final String linkTarget = file.getLink();
    // final String linkTargetBaseName =
    // getPathControl().basename(linkTarget);
    // //System.out.println("link target basename: " + linkTargetBaseName);
    // if( linkTarget != null ) {
    // String linkContaingPath =
    // getPathControl().getPathLevelUp(linkTarget);
    // FTPFile[] targetFiles = null;
    // if( linkContaingPath.equals("") || linkContaingPath.equals(cwd) ) {
    // targetFiles = filesInDir;
    // } else {
    // //System.out.println("check dir : " + linkContaingPath);
    // targetFiles = ftpClient.listFiles(linkContaingPath);
    // }
    //
    //
    // if( targetFiles != null ) {
    // for(int i=0; i<targetFiles.length; i++) {
    // //System.out.println("> " + targetFiles[i].getName());
    // if( targetFiles[i].getName().equals(linkTargetBaseName) ) {
    // if( targetFiles[i].isDirectory() ) {
    // prop.setDirectoryFlag(true);
    // }
    // break;
    // }
    // }
    // }
    // }
    // }

    if (file.isSymbolicLink()) {
        final String linkTarget = file.getLink();
        boolean result = ftpClient.changeWorkingDirectory(linkTarget);
        if (result) {
            prop.setDirectoryFlag(true);
        }
        ftpClient.changeWorkingDirectory(cwd);
    }

    return prop;
}

From source file:net.sf.webphotos.gui.util.FtpClient.java

/**
 * Executa o comando FTP. Utiliza o mtodo
 * {@link net.sf.webphotos.sync.Sync#loadSyncCache() loadSyncCache}() para
 * fazer o load do arquivos com os comandos de FTP. Checa se existem
 * comandos a executar, caso positivo, tenta a conexo com FTP e executa os
 * comandos (UPLOAD, DELETE ou DOWNLOAD).
 *//* ww w.ja v a  2 s . com*/
@Override
public void run() {

    String acao;
    String albumID;
    String arquivo;
    long tamanho;

    String arqOrigem;
    String arqDestino;

    Object streamOrigem = null;
    Object streamDestino = null;

    String ultimoID = "";
    int i, j = 0;

    String diretorioDownload = null;
    // loadSyncCache arquivo
    ftp.loadSyncCache();
    modeloTabela.refresh(ftp.getListaArquivos());
    modeloTabela.fireTableDataChanged();

    // tem algum comando  executar ?
    if (tabela.getRowCount() == 0) {
        ftp.disconnect("No h comandos ftp");
        return;
    }

    // tenta a conexao com FTP
    if (!ftp.connect()) {
        return;
    }
    preProcessBatch();
    modeloTabela.refresh(ftp.getListaArquivos());
    modeloTabela.fireTableDataChanged();
    barra.setMaximum(Integer.parseInt(Long.toString(totalBytes)));

    // executa os comandos
    for (i = 0; i < tabela.getRowCount(); i++) {

        lblArquivos.setText(i + 1 + " / " + tabela.getRowCount());
        tabela.setRowSelectionInterval(i, i);
        tabela.scrollRectToVisible(tabela.getCellRect(i + 1, 0, true));
        tabela.repaint();
        acao = tabela.getValueAt(i, 1).toString();
        albumID = tabela.getValueAt(i, 2).toString();
        arquivo = tabela.getValueAt(i, 4).toString();

        // ajusta o diretrio para /ftpRoot/albumID
        // recebe a lista de arquivos 
        if (!ultimoID.equals(albumID)) {
            Util.log("Mudando para o diretrio " + albumID);
            try {
                ftp.cd(albumID);
                remoteFiles = ftp.listFiles();
                diretorioDownload = null;
            } catch (IOException ioE) {
                Util.log("[FtpClient.run]/ERRO: comando no foi aceito ao listar o diretrio " + albumID
                        + " desconectando");
                ftp.disconnect("no foi possivel entrar no diretorio");
            } catch (SyncException se) {
                Util.log(se.getMessage());
                ftp.disconnect("no foi possivel entrar no diretorio");
            }
        }

        // UPLOAD
        switch (acao) {
        case "enviar":
            if (diretorioDownload == null) {
                diretorioDownload = albunsRoot.getAbsolutePath() + File.separator + albumID;
            }
            arqOrigem = diretorioDownload + File.separator + arquivo;
            Util.out.println(arqOrigem + " -> " + arquivo);
            try {
                streamOrigem = new FileInputStream(arqOrigem);
                streamDestino = new BufferedOutputStream(ftp.storeFileStream(arquivo), ftp.getBufferSize());
                this.transfereArquivo((InputStream) streamOrigem, (OutputStream) streamDestino,
                        Long.parseLong(tabela.getValueAt(i, 5).toString()));
                tabela.setValueAt("ok", i, 0);
            } catch (FileNotFoundException ioE) {
                Util.log("[FtpClient.run]/AVISO: " + arqOrigem + " no foi encontrado.");
                tabela.setValueAt("ok - ne", i, 0);
            } catch (IOException ioE) {
                Util.log("[FtpClient.run]/ERRO: erro na transmisso de " + arqOrigem);
                ioE.printStackTrace(Util.out);
                tabela.setValueAt("erro", i, 0);
            } catch (NumberFormatException e) {
                Util.err.println("Erro inexperado: " + e.getMessage());
                e.printStackTrace(Util.out);
                tabela.setValueAt("erro", i, 0);
            } finally {
                try {
                    ftp.printWorkingDirectory();
                } catch (IOException e) {
                }
                try {
                    ((OutputStream) streamDestino).close();
                    ((InputStream) streamOrigem).close();
                } catch (Exception e) {
                }
            }
            posTransfer(i);

            // DELETE
            break;
        case "apagar":
            // apaga o diretorio inteiro
            if (arquivo.equals("* todos")) {
                try {
                    for (FTPFile remote : remoteFiles) {
                        ftp.deleteFile(remote.getName());
                        Util.log("Removendo arquivo remoto " + remote.getName());
                        transmitido += remote.getSize();
                        Util.out.println("Processado " + transmitido + " de " + totalBytes);
                        barra.setValue((int) transmitido);
                        lblKbytes.setText(Math.round((float) transmitido / 1024) + " Kb");
                    }

                    // Volta para o diretrio principal
                    ftp.changeWorkingDirectory(ftpRoot);
                    // finalmente remove o diretorio
                    ftp.removeDirectory(albumID);
                    tabela.setValueAt("ok", i, 0);

                } catch (Exception e) {
                    tabela.setValueAt("erro", i, 0);
                    log.error(e);
                }
                // apaga somente uma foto
            } else {
                for (FTPFile remote : remoteFiles) {
                    if (remote.getName().equals(arquivo)) {
                        remoteFile = remote;
                        break;
                    }
                }
                //remoteFile=RemoteFile.findRemoteFile(remoteFiles,arquivo);
                if (remoteFile == null) {
                    tabela.setValueAt("ok - ne", i, 0);
                } else {
                    tabela.setValueAt(Long.toString(remoteFile.getSize()), i, 5);
                    try {
                        ftp.deleteFile(arquivo);
                        tabela.setValueAt("ok", i, 0);

                        posTransfer(i);
                    } catch (IOException | NumberFormatException e) {
                        tabela.setValueAt("erro", i, 0);
                    }
                }
            }

            // DOWNLOAD - recebe os arquivos (pr listado e calculado)
            break;
        // fim if
        case "receber":
            try {
                // cada vez que muda o diretrio, a varivel diretrioDownload  nula
                if (diretorioDownload == null) {
                    diretorioDownload = albunsRoot.getAbsolutePath() + File.separator + albumID;
                    File temp = new File(diretorioDownload);

                    if (!temp.isDirectory()) {
                        temp.mkdir();
                        Util.log("Criando diretrio " + diretorioDownload);
                    }
                    temp = null;
                }
                arqDestino = diretorioDownload + File.separator + arquivo;
                Util.out.println(arquivo + " -> " + arqDestino);

                streamOrigem = new BufferedInputStream(ftp.retrieveFileStream(arquivo), ftp.getBufferSize());

                streamDestino = new FileOutputStream(arqDestino);

                this.transfereArquivo((InputStream) streamOrigem, (OutputStream) streamDestino,
                        Long.parseLong(tabela.getValueAt(i, 5).toString()));
                tabela.setValueAt("ok", i, 0);

                // calcula porcentagem e atualiza barra
                posTransfer(i);

            } catch (IOException ioE) {
                Util.err.println("Erro de transmisso: " + ioE.getMessage() + " "
                        + ((CopyStreamException) ioE).getIOException().getMessage());
                tabela.setValueAt("erro", i, 0);
                log.error(ioE);
            } catch (NumberFormatException e) {
                Util.err.println("Erro: ");
                log.error(e);
                tabela.setValueAt("erro", i, 0);
            } finally {
                try {
                    ftp.printWorkingDirectory();
                } catch (IOException e) {
                }
                try {
                    ((InputStream) streamOrigem).close();
                    ((OutputStream) streamDestino).close();
                } catch (IOException e) {
                }
            }
            break;
        }

        ultimoID = albumID;
    } // fim for
    ftp.disconnect("transmisso terminada");
}

From source file:net.sf.webphotos.gui.util.FtpClient.java

private void preProcessBatch() {
    String acao;// w w w  .jav a2  s .c o  m
    Arquivo tmpArq;
    int i, j = 0;

    // calcula quantidade de bytes a transmitir (upload e download somente)
    for (i = 0; i < tabela.getRowCount(); i++) {
        acao = tabela.getValueAt(i, 1).toString();
        if (acao.equals("enviar")) {
            totalBytes += Long.parseLong(tabela.getValueAt(i, 5).toString());
        }
        if (acao.equals("receber")) {
            Util.log("Calculando bytes a serem recebidos (lbum " + tabela.getValueAt(i, 2) + ")");
            tmpArq = (Arquivo) ftp.getListaArquivos().get(i);

            if (tmpArq.getNomeArquivo().equals("* todos")) {
                // Baixando todo o lbum
                try {
                    Util.out.println("Convertendo: " + tmpArq.getAlbumID());
                    // remove o tem atual e diminui 
                    // o marcador aps a remoo
                    ftp.getListaArquivos().remove(i--);
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        ftp.getListaArquivos().add(new Arquivo(tmpArq.getLinhaComando(), 2, tmpArq.getAlbumID(),
                                tmpArq.getFotoID(), remote.getName(), remote.getSize()));
                        totalBytes += remote.getSize();
                    } // fim for
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            } else {
                // Baixando um arquivo
                try {
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = this.ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        if (tmpArq.getNomeArquivo().equals(remote.getName())) {
                            totalBytes += remote.getSize();
                            tmpArq.setTamanho(remote.getSize());
                            break;
                        }
                    } // fim for
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
        if (acao.equals("apagar")) {
            Util.log("Calculando bytes a serem apagados (lbum " + tabela.getValueAt(i, 2) + ")");
            tmpArq = (Arquivo) ftp.getListaArquivos().get(i);
            if (tmpArq.getNomeArquivo().equals("* todos")) {
                // Apagando todo o lbum
                try {
                    Util.out.println("Convertendo: " + tmpArq.getAlbumID());
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = this.ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        totalBytes += remote.getSize();
                    }
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            } else {
                // Apagando um arquivo
                try {
                    ftp.cd(Integer.toString(tmpArq.getAlbumID()));
                    remoteFiles = this.ftp.listFiles();
                    for (FTPFile remote : remoteFiles) {
                        if (tmpArq.getNomeArquivo().equals(remote.getName())) {
                            totalBytes += remote.getSize();
                            tmpArq.setTamanho(remote.getSize());
                            break;
                        }
                    }
                } catch (SyncException se) {
                    Util.log(se.getMessage());
                    ftp.disconnect("no foi possivel entrar no diretorio");
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }
}

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;//  w  w w  .  ja va  2 s.  c om
    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;
}