FTPClient下载文件失败,retrieveFile()方法replyCode = 550

Sip*_*eng 5 java ftp apache-commons-net

/*我在localhost上运行一个FTP服务器.当我下载文件时使用ftpClient.retrieveFile()方法,它的replyCode是550.我读了commons-net的API并找到了550 replyCode,定义是"public static final int FILE_UNAVAILABLE 550".但我无法从我的代码中找到问题.
谢谢你的帮助.

*/

    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;

    try {
        ftpClient.connect("192.168.1.102",2121);
        ftpClient.login("myusername", "12345678");
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        String remoteFileName = "ftpserver.zip";//this file in the rootdir
        fos = new FileOutputStream("f:/down.zip");
        ftpClient.setBufferSize(1024);
        ftpClient.enterLocalPassiveMode();
        ftpClient.enterLocalActiveMode();
        ftpClient.retrieveFile(remoteFileName, fos);  
        System.out.println("retrieveFile?"+ftpClient.getReplyCode());
        fos.close();
        ftpClient.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("??FTP??", e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 9

我发现Apache retrieveFile(...)有时不能使用超过一定限制的文件大小.为了克服这个问题,我会使用retrieveFileStream()代替.在下载之前,我已经设置了Correct FileType并将Mode设置为PassiveMode

所以代码看起来像

    ....
    ftpClientConnection.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClientConnection.enterLocalPassiveMode();
    ftpClientConnection.setAutodetectUTF8(true);

    //Create an InputStream to the File Data and use FileOutputStream to write it
    InputStream inputStream = ftpClientConnection.retrieveFileStream(ftpFile.getName());
    FileOutputStream fileOutputStream = new FileOutputStream(directoryName + "/" + ftpFile.getName());
    //Using org.apache.commons.io.IOUtils
    IOUtils.copy(inputStream, fileOutputStream);
    fileOutputStream.flush();
    IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(inputStream);
    boolean commandOK = ftpClientConnection.completePendingCommand();
    ....
Run Code Online (Sandbox Code Playgroud)


fre*_*crs 2

FTP 错误 550 未执行请求的操作。文件不可用、未找到、无法访问

所以我认为enconding有点奇怪,我没有设置控制编码并使用retrieveFile只是在java中发送一个普通的字符串。还有这一行:

ftpClient.retrieveFile(new String(remoteFileName.getBytes("ms932"),"ISO-8859-1"), fos);
Run Code Online (Sandbox Code Playgroud)

不执行任何操作,因为您正在从另一个字符串创建新的 Java 字符串。Java字符串以不同的编码保存在内存中,如果我没记错的话,与所有编码兼容。

另外,你使用的路径是错误的,请参阅:

String remoteFileName = "//ftpserver.zip";
Run Code Online (Sandbox Code Playgroud)

Ftp 将导致以 / 开头的路径出错,请尝试以下操作:

"ftpserver.zip"
Run Code Online (Sandbox Code Playgroud)

或者如果您有子目录,请尝试以下操作:

"subdir/myfile.zip"
Run Code Online (Sandbox Code Playgroud)

干杯