Skip to content

Instantly share code, notes, and snippets.

@vivisidea
Created July 30, 2012 09:50
Show Gist options
  • Save vivisidea/3205919 to your computer and use it in GitHub Desktop.
Save vivisidea/3205919 to your computer and use it in GitHub Desktop.
使用FTPClient将一个文件传输到ftp服务器
private FTPClient ftpClient = new FTPClient();
/**
* 传输文件到ftp服务器
* @param file
* @return
*/
private boolean uploadFile(File file) {
if(file == null || !file.exists()){
logger.error("文件不存在! file="+file);
return false;
}
CountingInputStream cis = null;
try{
ftpClient.connect(host, port);
ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode(); // 进入被动模式
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 需要指定文件传输类型,否则默认是ASCII类型,会导致二进制文件传输损坏
InputStream ins = new FileInputStream(file);
// 提示文件上传进度
final long fileSize = file.length();
cis = new CountingInputStream(ins){
private double progress = 0.0;
private double step = 0.1;
@Override
protected void beforeRead(int n){
try {
super.beforeRead(n);
} catch (IOException e) {
logger.error("error reading file.", e);
}
double ratio = 1.0 * getCount() / fileSize;
if(ratio >= progress){
logger.info(String.format("uploading %s of %s (%.0f%% completed)", getCount(), fileSize, ratio * 100));
progress += step;
}
}
};
return ftpClient.storeFile(file.getName(), cis);
}catch (Exception e) {
logger.error(String.format("ftp文件传输异常, file=%s", file), e);
return false;
}finally{
IOUtils.closeQuietly(cis);
try { ftpClient.logout(); } catch (Exception e) {} // keep quiet
try { ftpClient.disconnect(); } catch (IOException e) {}// keep quiet
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment