2017-03-29 50 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(); 
}