2013-03-21 73 views
-2

需要使用FTP從服務器下載文件,而不使用現有的庫和第三個奇偶校驗解決方案。我設法連接並登錄到服務器,傳輸類型模式(ASCII)和鈍化模式,所以我得到端口號並打開新的ServerSocket(端口)。但是當我調用RETR fileName時,我的程序在InputStream.readLine()上阻塞(在讀取服務器端口時,意味着服務器沒有響應)在調用RETR命令之前我忘記了什麼嗎?如何通過FTP下載文件java代碼

//PASV 
outputStream.println("pasv");  

//227 Entering Passive Mode(a1,a2,a3,a4,p1,p2) 
String response = inputStream.readLine(); 

// port = p1*256 + p2 
ServerSocket serverSocket = new ServerSocket(port); 

//RETR fileName 
outputStream.println("retr "+ fileName); 

//server no answer 
String reply = inputStream.readLine() 
+1

是這個家庭作業,因爲我無法想象爲什麼你不想使用現有的庫的另一個原因? – jtahlborn 2013-03-21 18:27:59

+1

查看被動模式和主動模式之間的區別。 – parsifal 2013-03-21 18:30:04

+0

是的,它的功課。不幸的是,現有的庫不允許。 – user2191697 2013-03-21 18:34:38

回答

0

FTP PASV命令不會打開客戶端上的插座中,IP和端口返回給客戶端從服務器基本上是告訴客戶端「好連接到我這個IP和端口」。請查看RFC 959瞭解實現細節。在JAVA中實現FTP客戶端並不是一個簡單的過程。

0
public void download(String remoteFile) { 


    FTPClient ftpClient = new FTPClient(); 

    try { 
     ftpClient.connect(server, 22); 
     ftpClient.login(ftpUser, ftpPassword); 
     ftpClient.enterLocalPassiveMode(); 
     ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 

     // APPROACH #1: using retrieveFile(String, OutputStream) 
     File downloadFile1 = new File("D:/ftpdosyam.txt"); 
     OutputStream outputStream = new BufferedOutputStream(
       new FileOutputStream(downloadFile1)); 
     boolean success = ftpClient.retrieveFile(remoteFile, outputStream); 
     outputStream.close(); 

     if (success) { 
      System.out.println("File #1 has been downloaded successfully."); 
     } 
    } catch (SocketException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
}