2017-03-29 52 views
-3

我必須改進一段必須與Java 1.6兼容的Java代碼,並且我正在尋找下面函數中fileoutputstream的替代方案。我正在使用apache.commons FTP包。Java 1.6的FileOutputStream替代方案

import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPReply; 

FTPClient ftp = null; 

public FTPFetch(String host, int port, String username, String password) throws Exception 
{ 

    ftp = new FTPClient(); 
    ftp.setConnectTimeout(5000); 
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); 
    int reply; 
    ftp.connect(host, port); 
    reply = ftp.getReplyCode(); 
    if (!FTPReply.isPositiveCompletion(reply)) 
    { 
     ftp.disconnect(); 
     throw new Exception("Exception in connecting to FTP Server"); 
    } 
    if (ftp.login(username, password)) 
    { 
     ftp.setFileType(FTP.BINARY_FILE_TYPE); 
     ftp.enterLocalActiveMode(); 
    } else 
    { 
     disconnect(); 
     errorLog.fatal("Remote FTP Login Failed. Username or Password is incorrect. Please update in configuration file."); 
     System.exit(1); 
    } 
} 

try (FileOutputStream fos = new FileOutputStream(destination)) 
    { 
     if (this.ftp.retrieveFile(source, fos)) 
     { 
      return true; 
     } else 
     { 
      return false; 
     } 
    } catch (IOException e) 
    { 
     return false; 
    } 
+9

'FileOutputStream' exists si nce JDK 1.0 – Berger

+2

注意:'if(condition){return true; } else {return false; }'和return條件相同;' –

+0

謝謝,我已經修改了代碼以在本地修復此問題。 – Tacitus86

回答

4

代碼不會在Java 1.6的編譯,因爲您使用try-與資源

試戴與資源聲明

試戴與資源語句是一個嘗試聲明一個或多個資源的語句。資源是程序結束後必須關閉的對象。 try-with-resources語句確保每個資源在語句結束時都關閉。任何實現了java.lang.AutoCloseable的對象(包含所有實現java.io.Closeable的對象)都可以用作資源。

...

在這個例子中,資源在try-與資源語句聲明是一個BufferedReader。聲明語句出現在try關鍵字後面的括號內。在Java SE 7和更高版本中,類BufferedReader實現了接口java.lang.AutoCloseable。由於BufferedReader實例是在try-with-resource語句中聲明的,因此無論try語句是正常還是突然完成(由於BufferedReader.readLine引發拋出IOException),它都將被關閉。

在Java SE 7之前,無論try語句是正常還是突然完成,都可以使用finally塊來確保資源已關閉。下面的示例使用finally塊來代替一試,與資源聲明:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

另一種方法是:

FileOutputStream fos = null; 
try { 
    fos = new FileOutputStream(destination); 

    if(this.ftp.retrieveFile(source, fos)) { 
    return true; 
    } else { 
    return false; 
    } 
} catch (IOException e) { 
    return false; 
} finally { 
    if(fos != null) 
    fos.close(); 
} 
+1

謝謝!接得好。 – Tacitus86

+0

確實。只需等待強制時間即可接受。 – Tacitus86

3

嘗試與 - 資源(try (AutoClosable ...))不可用在Java 6.省略,你應該沒問題,例如:

FileOutputStream fos = null; 
try { 
    fos = new FileOutputStream(destination); 
    return this.ftp.retrieveFile(source, fos); 
} catch (IOException e) { 
    return false; 
} finally { 
    if (fos != null) 
    fos.close(); 
}