2011-08-22 65 views
1

的Java文件上傳我上傳文件到服務器,但該文件是空的。(大小零字節)通過ftp零字節錯誤

 int reply; 
     ftp.connect(server,215); 
     ftp.login(username, Password); 
     System.out.println("Connected to " + server + "."); 
     System.out.print(ftp.getReplyString()); 
     reply = ftp.getReplyCode(); 
     if(!FTPReply.isPositiveCompletion(reply)) { 
       ftp.disconnect(); 
       System.err.println("FTP server refused connection."); 
     } 
     System.out.println("FTP server connected."); 
      ftp.setFileType(FTP.BINARY_FILE_TYPE); 
      ftp.enterLocalPassiveMode(); 

     InputStream input= new FileInputStream(source_file_path); 

     ftp.storeFile(dest_dir, input); 
     System.out.println(ftp.storeFile(dest_dir, input)); 
     System.out.println(ftp.getReplyString()); 

          input.close(); 

          ftp.logout(); 

回答

1

看着你的代碼,我認爲你正在使用的Jakarta Commons網。 如果其真正的,試試這個:

ftp.connect(address, port); 
boolean ft = ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
if(!ft) 
    throw new Exception("Error"); 
ftp.enterLocalPassiveMode(); or ftp.enterLocalActiveMode(); 
boolean log = ftp.login(user, password); 
//if log == true, then u are logged in 
ftp.storeFile(remote, local); 

而且,如果u想用一個進度條來獲得TE傳輸進度ü可以試試這個方法,而不是ftp.storeFile

InputStream stO = new BufferedInputStream(new FileInputStream(file), ftp.getBufferSize()); 
OutputStream stD = ftp.storeFileStream(file.getName()); 

        org.apache.commons.net.io.Util.copyStream(
        stO, 
        stD, 
        ftp.getBufferSize(), 
        file.length(), 
        new org.apache.commons.net.io.CopyStreamAdapter() 
        { 
         @Override 
         public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, 
           long streamSize) 
         { 
          try 
          { 
           pb.setMaximum((int)streamSize); 
           pb.setValue((int)totalBytesTransferred); 
          } 
          catch(Exception ex) 
          { 
           pb.setMaximum(-1); 
          } 
         } 
        }); 
        stO.close(); 
        stD.close(); 
        boolean ok = ftp.completePendingCommand(); 
        if(!ok) 
         throw new Exception("ERROR while sending the file"); 

PS:PB是JProgressBar

1

您正在存儲文件兩次。

ftp.storeFile(dest_dir, input); 
System.out.println(ftp.storeFile(dest_dir, input)); 

如果你還沒有重啓的輸入流,您呼叫的storeFile方法的第二個時間,輸入流是EOF,所以你要上傳的第二次文件將沒有內容,因此覆蓋第一個文件。

要打印的storeFile結果,你應該:

Object result = ftp.storeFile(dest_dir, input); 
System.out.println(result);