Java 1.6的FileOutputStream替代方案

Java 1.6的FileOutputStream替代方案,java,fileoutputstream,Java,Fileoutputstream,我必须改装一段java代码,该代码必须与Java1.6兼容,我正在以下函数中寻找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 FTPF

我必须改装一段java代码,该代码必须与Java1.6兼容,我正在以下函数中寻找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;
    }

该代码不在Java1.6中编译,因为您使用了try with资源

try with resources语句

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

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

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

另一种选择是:

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();
}
使用资源进行尝试(
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();
}

FileOutputStream
自JDK 1.0以来一直存在注意:
if(condition){return true;}否则{return false;}
返回条件相同谢谢,我修改了代码以在本地修复此问题。