Java FTPClient下载一个0字节的文件

Java FTPClient下载一个0字节的文件,java,Java,我试图从服务器下载一个文件,但它得到0字节 这是我的FTPDownload类 public boolean getFile(String filename){ try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(ftpAddress, ftpPort); ftpClient.login(ftpUser, ftpPass);

我试图从服务器下载一个文件,但它得到0字节

这是我的FTPDownload类

public boolean getFile(String filename){

        try {
        FTPClient ftpClient = new FTPClient();

            ftpClient.connect(ftpAddress, ftpPort);
            ftpClient.login(ftpUser, ftpPass);
            int reply = ftpClient.getReplyCode();
            //FTPReply stores a set of constants for FTP reply codes. 
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftpClient.disconnect();
                return false;

            }
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setBufferSize(1024*1024);

            String remoteFile = serverPath + filename;
            logger.debug("remote file is: "+remoteFile); //correct path
            File tempFile = new File(downloadDir+"temp.jar");
            logger.debug("file will be "+tempFile.toString()); //correctly created
            OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));

            ftpClient.retrieveFile(remoteFile, os);
            os.close();

            String completeJarName = downloadDir+jarName;
            //delete previous file
            File oldFile = new File(completeJarName);
            FileUtils.forceDelete(oldFile);


            //rename
            File newFile = new File(completeJarName);
            FileUtils.moveFile(tempFile, newFile);

             if (ftpClient.isConnected()) {
                 ftpClient.logout();
                 ftpClient.disconnect();

             }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("errore ftp", e);
            return false;
        } 

        return true;
    }

基本上,创建临时文件,然后取消上一个文件并重命名临时文件,但它是0字节。。。我无法理解哪里出了问题…

我使用apache.common进行FTP下载。这是代码,你可以试试

 public class FTPUtils {
 private String hostName = "";
 private String username = "";
 private String password = "";
 private StandardFileSystemManager manager = null;
 FileSystemOptions opts = null;

 public FTPUtils(String hostName, String username, String password) {
  this.hostName = hostName;
  this.username = username;
  this.password = password;
  manager = new StandardFileSystemManager();
 }
     private void initFTPConnection() throws FileSystemException {
  // Create SFTP options
  opts = new FileSystemOptions();
  // SSH Key checking
  SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
    opts, "no");
  // Root directory set to user home
  SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
  // Timeout is count by Milliseconds
  SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
 }

 public void onUpload(String ftpfolder, String localFilePath, String fileName) {
  File file = new File(localFilePath);
  if (!file.exists())
   throw new RuntimeException("Error. Local file not found");

  try {
   manager.init();
   // Create local file object
   FileObject localFile = manager.resolveFile(file.getAbsolutePath());

   String remoteFilePath = "/" + ftpfolder + "/" + fileName;
   // Create remote file object
   FileObject remoteFile = manager.resolveFile(
     createConnectionString(hostName, username, password,
       remoteFilePath), opts);
   // Copy local file to sftp server
   remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
   System.out.println("Done");
  } catch (Exception e) {
   // Catch and Show the exception
  } finally {
   manager.close();

  }
 }
public static String createConnectionString(String hostName,
   String username, String password, String remoteFilePath) {
  return "sftp://" + username + ":" + password + "@" + hostName + "/"
    + remoteFilePath;
 }

}我使用apache.common进行FTP下载。这是代码,你可以试试

 public class FTPUtils {
 private String hostName = "";
 private String username = "";
 private String password = "";
 private StandardFileSystemManager manager = null;
 FileSystemOptions opts = null;

 public FTPUtils(String hostName, String username, String password) {
  this.hostName = hostName;
  this.username = username;
  this.password = password;
  manager = new StandardFileSystemManager();
 }
     private void initFTPConnection() throws FileSystemException {
  // Create SFTP options
  opts = new FileSystemOptions();
  // SSH Key checking
  SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
    opts, "no");
  // Root directory set to user home
  SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
  // Timeout is count by Milliseconds
  SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
 }

 public void onUpload(String ftpfolder, String localFilePath, String fileName) {
  File file = new File(localFilePath);
  if (!file.exists())
   throw new RuntimeException("Error. Local file not found");

  try {
   manager.init();
   // Create local file object
   FileObject localFile = manager.resolveFile(file.getAbsolutePath());

   String remoteFilePath = "/" + ftpfolder + "/" + fileName;
   // Create remote file object
   FileObject remoteFile = manager.resolveFile(
     createConnectionString(hostName, username, password,
       remoteFilePath), opts);
   // Copy local file to sftp server
   remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
   System.out.println("Done");
  } catch (Exception e) {
   // Catch and Show the exception
  } finally {
   manager.close();

  }
 }
public static String createConnectionString(String hostName,
   String username, String password, String remoteFilePath) {
  return "sftp://" + username + ":" + password + "@" + hostName + "/"
    + remoteFilePath;
 }

}BufferedOutputStream将数据写入内部缓冲区,因此您可能需要在关闭前刷新输出流:

OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));

ftpClient.retrieveFile(remoteFile, os);
os.flush();
os.close();
另一个提示:

  • 始终为缓冲流指定缓冲区大小(通常为8Kb的倍数)

  • 实例化流时始终使用try with resources指令,并让它们自动关闭

  • 未经适当处理,不得留下
    catch
    子句。异常应该是固定的(如果您希望程序从该异常中恢复),或者是向上传播的(默认情况下,是传播的)。只有原木不太可能是最好的治疗方法

BufferedOutputStream将数据写入内部缓冲区,因此您可能需要在关闭前刷新输出流:

OutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile));

ftpClient.retrieveFile(remoteFile, os);
os.flush();
os.close();
另一个提示:

  • 始终为缓冲流指定缓冲区大小(通常为8Kb的倍数)

  • 实例化流时始终使用try with resources指令,并让它们自动关闭

  • 未经适当处理,不得留下
    catch
    子句。异常应该是固定的(如果您希望程序从该异常中恢复),或者是向上传播的(默认情况下,是传播的)。只有原木不太可能是最好的治疗方法

我不确定,但尝试在
ftpClient.retrieveFile
之后但在
os.close()
之前刷新输出流
os.flush()
我不确定,但尝试在
ftpClient.retrieveFile
之后但在
os.close()之前刷新输出流
。您可以解决这个问题吗?您确定这是为了下载文件而不是将文件上载到服务器吗?是的,这是我现有的代码。我已经使用了我的目的你确定这是下载,而不是上传一个文件到服务器?是的,这是我现有的代码。我已经用过了