2010-09-13 187 views
1

我有一段代碼在下面用java上傳一個文件,代碼的功能正常,但是在打開輸出流時它會掛起很長時間。URLConnection使用FTP url調用getOutputStream的速度很慢

// open file to upload 
InputStream filein = new FileInputStream("/path/to/file.txt"); 

// connect to server 
URL url = new URL("ftp://user:[email protected]/dir/file.txt"); 
URLConnection urlConn = url.openConnection(); 
urlConn.setDoOutput(true); 

// write file 

// HANGS FROM HERE 
OutputStream ftpout = urlConn.getOutputStream(); 
// TO HERE for about 22 seconds 

byte[] data = new byte[1024]; 
int len = 0; 

while((len = filein.read(data)) > 0) { 
ftpout.write(data,0, len); 
} 

// close file     
filein .close(); 
ftpout.close(); 

在這個例子中URLConnection.getOutputStream()方法繼續正常掛起之前約22秒,該文件被上傳成功。在這種情況下,該文件只有4個字節,只是一個文本文件,其中包含「test」字樣,並且代碼在上載開始之前掛起,因此它不會因爲花費時間來上傳文件。

這隻有當連接到一臺服務器時發生,當我嘗試一個不同的服務器時,它的速度可能很快,我希望這會導致我認爲這是服務器配置問題,在這種情況下,此問題可能更適合服務器故障,但是如果我從FTP客戶端上傳(在我的情況下是FileZilla),它可以正常工作,因此可以通過代碼來解決這個問題。

任何想法?

回答

1

我已經通過切換使用Commons Net FTPClient來解決這個問題,它不會出現將代碼更改爲下面的相同問題。

  InputStream filein = new FileInputStream(new File("/path/to/file.txt")); 

      // create url 
    FTPClient ftp = new FTPClient(); 
    ftp.connect(host); 
    ftp.login(user, pass); 

    int reply = ftp.getReplyCode(); 
    if(!FTPReply.isPositiveCompletion(reply)) { 
     ftp.disconnect(); 
     System.err.println("FTP server refused connection."); 
     return; 
    } 

    OutputStream ftpout = ftp.appendFileStream("text.txt"); 

    // write file 
    byte[] data = new byte[1024]; 
    int len = 0; 

    while((len = filein.read(data)) > 0) { 
     ftpout.write(data,0, len); 
    } 

    filein.close(); 
    ftpout.close(); 
    ftp.logout();