简体   繁体   English

在Java上下载FTP文件夹(使用FTPClient Apache Commons Net 3.6 API)

[英]Download FTP folder on Java (Using FTPClient Apache Commons Net 3.6 API)

Im searching how to download the "www" folder on a FTP server using java. 我正在搜索如何使用java在FTP服务器上下载“ www”文件夹。 I tried to zip the folder and then download the file with "Retrieve file" method from FTPClient but I cant find some method to do this. 我尝试压缩文件夹,然后使用FTPClient中的 “检索文件”方法下载文件,但是我找不到执行此操作的方法。 I appreciate any help, thanks. 感谢您的帮助,谢谢。

My Backup FTP method code: 我的备份FTP方法代码:

public void metodoBackupFtp(String host, String usr, String pass, String carpetaRemota, String destino)
        throws InterruptedException {
    // TODO Comprobar si seria posible comprimir el archivo antes de descargarlo
    // *Nota al parecer no es posible con
    // Ftp client, aun asi se deja el metodo de compresion sin probar

    boolean connected, disconnected;
    try {
        FTPClient clienteFtp = new FTPClient();
        System.err.println("Datos de conexión\nHost:" + host + "\nUser:" + usr + "\nPass:" + pass);
        clienteFtp.connect(host);
        connected = clienteFtp.login(usr, pass); // TODO ya se realiza una conexión inicial correcta
        clienteFtp.enterLocalPassiveMode();
        clienteFtp.setFileType(FTP.BINARY_FILE_TYPE);
        if (connected) {
            System.out.println("Conectado al FTP!");
            JOptionPane.showMessageDialog(frame, "Conectado al FTP => " + host, "Conectado al FTP!",
                    JOptionPane.INFORMATION_MESSAGE);
            System.err.println("Descarga de carpeta Carpeta Remota: " + carpetaRemota + "Destino: " + pathDestino);

        } else {
            JOptionPane.showMessageDialog(frame,
                    "No se ha podido establecer una conexión (Revisa los datos de conexión)",
                    "Fallo la conexión al FTP => " + host, JOptionPane.ERROR_MESSAGE);
        }
        // Thread.sleep(10000); //Para comprobar que se mantiene la conexion
        // Muestra la lista de archivos del raiz FTP en la consola
        clienteFtp.enterLocalPassiveMode();

        FTPFile[] files = clienteFtp.listFiles();

        String[] sfiles = null;
        if (files != null)
        {
            sfiles = new String[files.length];
            for (int i = 0; i < files.length; i++)
            {
                System.out.println(sfiles[i] = files[i].getName());

            }
}
        disconnected = clienteFtp.logout();
        if (disconnected) {
            JOptionPane.showMessageDialog(frame, "Desconectado de " + host, "Logout",
                    JOptionPane.INFORMATION_MESSAGE);
        }
        clienteFtp.disconnect();
    } catch (SocketException e) {
        JOptionPane.showMessageDialog(frame, "Fallo la conexión al FTP => " + host, "Error del servidor",
                JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {

    }

}

I do this class to solve the problem. 我上这堂课来解决问题。 I did not find any way to zip but I hope It can help. 我没有找到任何压缩方法,但我希望它能有所帮助。 Sorry for some spanish variable name. 抱歉,有些西班牙变量名。

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**
* To Download folder from FTP Server using FTPClient library.
* 
* @author Hadri
* @version 1.0
*/
public class FTPDown {

/**
 * Download a file
 *
 * @param clienteFTP
 * 
 * @param pathRemoto
 *            Path  FTP
 * @param archivoLocal
 *            Path from file
 * @return true if download correctly
 * @throws IOException
 * 
 */

public static boolean retrieveFile(FTPClient clienteFTP, String pathRemoto, String archivoLocal)
        throws IOException {
    DBDataBackup info = new DBDataBackup();
    System.err.println("RetrieveFile");
    System.err.println("Path remoto:" + pathRemoto + "Path guardado: " + archivoLocal);
    info.consoleArea.append("RetrieveFile\n");
    info.consoleArea.append("Path remoto:" + pathRemoto + "Path guardado: " + archivoLocal + "\n");

    File archivoDescarga = new File(archivoLocal);
    File directorio = archivoDescarga.getParentFile();

    if (!directorio.exists()) {
        info.consoleArea.append("Archivo: " + directorio.getName() + "\n");
        directorio.mkdir();
    }
    try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(archivoDescarga))) {
        clienteFTP.setFileType(FTP.BINARY_FILE_TYPE);
        return clienteFTP.retrieveFile(pathRemoto, outputStream);
    } catch (IOException ex) {
        throw ex;
    }
}

/**
 * Download folder from FTP
 *
 * @param clienteFtp
 *            FTPClient to use
 * @param directorioRemoto
 *           Folder to donwload
 *
 * 
 * @param directorioLocal
 *           Path where it saves
 * @throws IOException
 *             Exception
 */
public static void retrieveDir(FTPClient clienteFtp, String directorioRemoto, String directorioLocal)
        throws IOException {
    directorioLocal += "/www";
    DBDataBackup info = new DBDataBackup();
    System.err.println("RetrieveDir");
    info.consoleArea.append("RetrieveDir\n");
    System.err.println("Path remoto:" + directorioRemoto + "Path guardado: " + directorioLocal);
    info.consoleArea.append("Path remoto:" + directorioRemoto + "Path guardado: " + directorioLocal + "\n");
    FTPFile[] ftpFiles = clienteFtp.listFiles(directorioRemoto);
    if (ftpFiles == null || ftpFiles.length == 0) {
        return;
    }
    for (FTPFile ftpFile : ftpFiles) {
        info.consoleArea.append("Directorio: " + ftpFile.getName() + "\n");
        String ftpFileNombre = ftpFile.getName();
        if (ftpFileNombre.equals(".") || ftpFileNombre.equals("..")) {

            continue;
        }
        String archivoLocal = directorioLocal + "/" + ftpFileNombre;
        String archivoRemoto = directorioRemoto + "/" + ftpFileNombre;
        if (ftpFile.isDirectory()) {

            File nuevoDirectorio = new File(archivoLocal);
            nuevoDirectorio.mkdirs();

            retrieveDir(clienteFtp, archivoRemoto, archivoLocal);
        } else {

            retrieveFile(clienteFtp, archivoRemoto, archivoLocal);
        }
    }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 apache.commons.net.ftp.FTPClient未将文件上传到所需的文件夹 - apache.commons.net.ftp.FTPClient not uploading the file to the required folder 使用org.apache.commons.net.ftp.FTPClient保护FTP - Secure FTP with org.apache.commons.net.ftp.FTPClient 使用org.apache.commons.net.ftp.FTPClient从AsyncTask类登录FTP时出错 - Error when logging into FTP from AsyncTask class using org.apache.commons.net.ftp.FTPClient 致命异常:main java.lang.NoClassDefFoundError:org.apache.commons.net.ftp.FTPClient Android Studio - FATAL EXCEPTION: main java.lang.NoClassDefFoundError: org.apache.commons.net.ftp.FTPClient Android Studio 如何使用“ org.apache.commons.net.ftp.FTPClient”解决异常 - How to solve exception with “org.apache.commons.net.ftp.FTPClient” org.apache.commons.net.ftp.FTPClient listFiles()的问题 - Issue with org.apache.commons.net.ftp.FTPClient listFiles() 如何导入 org.apache.commons.net.ftp.FTPClient - How to import org.apache.commons.net.ftp.FTPClient 使用 Apache Commons Net FTPClient 从 FTP 服务器循环读取多个文件 - Reading multiple files in loop from FTP server using Apache Commons Net FTPClient 无法使用 Apache Commons FTPClient 访问 FTP 服务器上的子文件夹 - Can't access subfolders on FTP server using Apache Commons FTPClient 下载Java中的整个FTP目录(Apache Net Commons) - Download entire FTP directory in Java (Apache Net Commons)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM