如何使用“ org.apache.commons.net.ftp.FTPClient”解决异常

时间:2019-04-28 01:12:40

标签: java nullpointerexception ftp-client

我不确定这是否是我遇到的类似问题,因为它没有声明异常: Issue with org.apache.commons.net.ftp.FTPClient listFiles()

我正在尝试使用此class FTPUtil下载根文件夹: https://www.codejava.net/java-se/ftp/how-to-download-a-complete-folder-from-a-ftp-server

行中的

     FTPFile[] subFiles = ftpClient.listFiles(dirToList); 我收到此异常:

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.net.InetAddress.getHostAddress()' on a null object reference
    at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:938)
    at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:785)
    at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3409)
    at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3339)
    at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:3016)
    at com.censored.FTPUtil.downloadDirectory(FTPUtil.java:39)

我不太了解哪个Object为null,为什么。 在String parentDir尝试"""\"时,都得到了相同的结果,我认为输入的内容是错误的。
FTP服务器运行良好,我看到程序成功登录,并且文件zilla可以访问该文件夹。

编辑:

这是我正在使用的链接中的课程:

package com.censored;

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;

/**
 * This utility class implements a method that downloads a directory completely
 * from a FTP server, using Apache Commons Net API.
 *
 * @author www.codejava.net
 *
 */
public class FTPUtil {

    /**
     * Download a whole directory from a FTP server.
     * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
     * @param parentDir Path of the parent directory of the current directory being
     * downloaded.
     * @param currentDir Path of the current directory being downloaded.
     * @param saveDir path of directory where the whole remote directory will be
     * downloaded and saved.
     * @throws IOException if any network or IO error occurred.
     */
    public static void downloadDirectory(FTPClient ftpClient, String parentDir,
            String currentDir, String saveDir) throws IOException {
        String dirToList = parentDir;
        if (!currentDir.equals("")) {
            dirToList += "/" + currentDir;
        }

        FTPFile[] subFiles = ftpClient.listFiles(dirToList); //This line gives the Exception

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    // skip parent directory and the directory itself
                    continue;
                }
                String filePath = parentDir + "/" + currentDir + "/"
                        + currentFileName;
                if (currentDir.equals("")) {
                    filePath = parentDir + "/" + currentFileName;
                }

                String newDirPath = saveDir + parentDir + File.separator
                        + currentDir + File.separator + currentFileName;
                if (currentDir.equals("")) {
                    newDirPath = saveDir + parentDir + File.separator
                              + currentFileName;
                }

                if (aFile.isDirectory()) {
                    // create the directory in saveDir
                    File newDir = new File(newDirPath);
                    boolean created = newDir.mkdirs();
                    if (created) {
                        System.out.println("CREATED the directory: " + newDirPath);
                    } else {
                        System.out.println("COULD NOT create the directory: " + newDirPath);
                    }

                    // download the sub directory
                    downloadDirectory(ftpClient, dirToList, currentFileName,
                            saveDir);
                } else {
                    // download the file
                    boolean success = downloadSingleFile(ftpClient, filePath,
                            newDirPath);
                    if (success) {
                        System.out.println("DOWNLOADED the file: " + filePath);
                    } else {
                        System.out.println("COULD NOT download the file: "
                                + filePath);
                    }
                }
            }
        }
    }

    /**
     * Download a single file from the FTP server
     * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
     * @param remoteFilePath path of the file on the server
     * @param savePath path of directory where the file will be stored
     * @return true if the file was downloaded successfully, false otherwise
     * @throws IOException if any network or IO error occurred.
     */
    public static boolean downloadSingleFile(FTPClient ftpClient,
            String remoteFilePath, String savePath) throws IOException {
        File downloadFile = new File(savePath);

        File parentDir = downloadFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdir();
        }

        OutputStream outputStream = new BufferedOutputStream(
                new FileOutputStream(downloadFile));
        try {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            return ftpClient.retrieveFile(remoteFilePath, outputStream);
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

这是我的代码调用它(检查了我没有权限显示完整课程的无关内容):

val server = "10.0.2.2"  // Because of Emulator
val port = 8080 //yeah I know not standard port, this will change
val user = "censored"
val pass = "censored"        

val remoteDirPath = ""   //also tried "/"
val saveDirPath = File(myFilesDir, "fromFTP/").absolutePath   //ignore myFilesDir the Debuger shows that its set correct and it isnt relevant before the Exception

val ftpClient = FTPClient()



    try {
        // connect and login to the server
        ftpClient.connect(server, port)
        ftpClient.login(user, pass)

        // use local passive mode to pass firewall
        ftpClient.enterLocalPassiveMode()

        println("Connected")

        FTPUtil.downloadDirectory(ftpClient, remoteDirPath, "", saveDirPath) //this line is the one giving the exception

        // log out and disconnect from the server
        ftpClient.logout()
        ftpClient.disconnect()

        println("Disconnected")
    } catch (ex: IOException) {
        ex.printStackTrace()
    }

更新: 在调试过程中,我发现类if中的这个FTPClient extends FTP是正确的:

 if (__remoteVerificationEnabled && !verifyRemote(socket))
        {
            socket.close();

            throw new IOException(
                    "Host attempting data connection " + socket.getInetAddress().getHostAddress() +
                    " is not same as server " + getRemoteAddress().getHostAddress());
        }

        return socket;

我认为socket.getInetAddress()会导致异常(在外部异常内部),因为Socket已关闭?这是否意味着FTPClient本身包含错误?但是,我认为我的问题的解决方案是if (__remoteVerificationEnabled && !verifyRemote(socket))为true,因此某种程度上如果必须变为false,就可以解决。为什么会这样呢?这是什么样的验证?

2 个答案:

答案 0 :(得分:0)

好吧,我认为这只是一种解决方法,但是解决方案似乎是在广告这行:ftpClient.setRemoteVerificationEnabled(false);

阅读问题中的“更新”部分,以了解如何找到此解决方案。

答案 1 :(得分:0)

我认为你是对的。这是FTPClient中的错误。

如果套接字未打开,则记录

socket.getInetAddress()引发NullPointerException。在调用socket.close()之后立即调用此方法。