Java 1.6的FileOutputStream替代方案

时间:2017-03-29 13:53:14

标签: java fileoutputstream

我必须改进一段必须与Java 1.6兼容的java代码,并且我正在寻找以下函数中fileoutputstream的替代方案。我正在使用apache.commons FTP包。

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;
    }

2 个答案:

答案 0 :(得分:4)

代码无法在Java 1.6中编译,因为您使用了try-with-resources

  

try-with-resources Statement

     

try-with-resources语句是一个声明一个或多个资源的try语句。资源是在程序完成后必须关闭的对象。 try-with-resources语句确保在语句结束时关闭每个资源。任何实现 java.lang.AutoCloseable 的对象(包括实现java.io.Closeable的所有对象)都可以用作资源。

     

...

     

在此示例中,try-with-resources语句中声明的资源是BufferedReader。声明语句出现在try关键字后面的括号内。 Java SE 7及更高版本中的类 BufferedReader 实现了接口 java.lang.AutoCloseable 。因为BufferedReader实例是在try-with-resource语句中声明的,所以无论try语句是正常还是突然完成(由于BufferedReader.readLine方法抛出IOException),它都将被关闭。

     

在Java SE 7之前,您可以使用finally块来确保资源已关闭,无论try语句是正常还是突然完成。以下示例使用finally块而不是try-with-resources语句:

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 :(得分: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();
}