2016-09-16 3 views
0

나는 서버에서 파일을 다운로드하기 위해 노력하고있어,하지만 0 바이트를 얻을 ...이FTPClient은 0 바이트 파일을

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; 
    } 

기본적으로 내 FTPDownload 클래스는

이다, 임시 저런 다운로드 도착하면 이전 파일이 취소되고 임시 파일의 이름이 바뀌었지만 0 바이트입니다 ... 어디서 잘못되었는지 이해할 수 없습니다 ...

+0

출력 스트림'os.flush()'를'ftpClient.retrieveFile' 다음에'os.close()'전에 플러시하려고합니다. – Shadov

답변

0

FTP 다운로드에 apache.common을 사용했습니다. 여기 코드는, 당신은 시도 할 수

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; 
} 

}

+0

다운로드하고 서버에 파일을 업로드하지 않으셨습니까? – besmart

+0

예이 코드는 기존 코드입니다. 나는 내 목적을 위해 사용했다. –

0

당신은 아마 닫기 전에 높이 OutputStream에 필요하므로의 BufferedOutputStream가, 내부 버퍼에 데이터를 기록 :

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

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

또 다른 팁 :

  • 항상 부 ffered 스트림은 버퍼 크기 (일반적으로 8Kb의 배수)입니다.

  • 스트림을 인스턴스화 할 때 항상 try-with-resources 명령을 사용하고 자동으로 닫히도록하십시오.

  • 적절한 치료없이 catch 절을 그대로 두지 마십시오. 예외는 으로 고정 (해당 예외에서 프로그램을 복구하려는 경우) 이 전파되어이 상향 (기본적으로 전파 됨)되어야합니다. 로그만으로는 최상의 치료법이 될 수 없습니다.
관련 문제