Skip to content

Instantly share code, notes, and snippets.

@akari0624
Last active February 1, 2018 07:10
Show Gist options
  • Save akari0624/fa35c893555ce49b82257ed91e5f227f to your computer and use it in GitHub Desktop.
Save akari0624/fa35c893555ce49b82257ed91e5f227f to your computer and use it in GitHub Desktop.
JAVA Apache FTPClient example - a method for retrieve file from FTPServer
public boolean getFileFromFTP_ServerToThePath(Properties ftpProp){
FTPClient ftpClient = null;
OutputStream fos = null;
boolean isGetFileFromFTP_ServerToThePathSuccess = false;
try{
ftpClient = new FTPClient();
ftpClient.connect(
(String)ftpProp.get(IP),
Integer.parseInt((String)ftpProp.get(PORT))
);
ftpClient.login( (String)ftpProp.get(USER_NAME), (String)ftpProp.get(PASSWORD));
//底下這兩行必須寫 不然會出錯
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
int reply = ftpClient.getReplyCode();
m_Logger.info("FTP connection status code :"+reply);
if(! FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
throw new IOException("連接FTP server時失敗 請檢查 FTP serverIP, PORT, 帳號密碼");
};
fos = new BufferedOutputStream(new FileOutputStream(getLocalFilePath(ftpProp)));
String remoteFilePath = getFilePath(ftpProp);
m_Logger.info("remoteFilePath :"+remoteFilePath);
isGetFileFromFTP_ServerToThePathSuccess =
ftpClient.retrieveFile(remoteFilePath, fos);
}catch(IOException e){
m_Logger.error("發生IOException!! :"+e.getMessage());
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException ioe1) {
m_Logger.error("關閉下載檔案的FileOutputStream時發生錯誤! : "+ioe1.getMessage());
}
}
if(ftpClient != null && ftpClient.isConnected()){
try {
ftpClient.disconnect();
} catch (IOException ioe2) {
m_Logger.error("關閉FTP連線時失敗! : "+ioe2.getMessage());
}
}
}
return isGetFileFromFTP_ServerToThePathSuccess;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment