1、连接ftp

       FTPClient ftpClient = new FTPClient();
ftpClient.connect(host,port);
ftpClient.login(userName, password);
ftpClient.setControlEncoding(encoding);
ftpClient.changeWorkingDirectory(workDir);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置上传文件类型为二进制,否则将无法打开文件
ftpClient.enterLocalPassiveMode();

2、从ftp下载文件

        String base64;
InputStream inputStream = null; try {
        ///防止中文乱码
if (!StringUtils.isEmpty(remotDir)){
remoteFileName = new String(remotDir.getBytes("GBK"), "iso-8859-1")+
File.separator+new String(remoteFileName.getBytes("GBK"), "iso-8859-1");
}else{
remoteFileName = new String(remoteFileName.getBytes("GBK"), "iso-8859-1");
}
//获取待读文件输入流
inputStream = ftpClient.retrieveFileStream(remoteFileName);
//inputStream.available() 获取返回在不阻塞的情况下能读取的字节数,正常情况是文件的大小
byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes);//将文件数据读到字节数组中
Base64.Encoder encoder = Base64.getEncoder();
base64 = encoder.encodeToString(bytes);//将字节数组转成base64字符串
log.info("read file {} success",remoteFileName);
// ftpClient.logout();
} catch (IOException e) {
log.error("read file fail ----->>>{}",e.getCause());
return null;
}finally {
if (null!=inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

3、向ftp上传文件

 try {
if (!StringUtils.isEmpty(remoteDir)){
originName = new String(remoteDir.getBytes("GBK"),"iso-8859-1")+File.separator+
new String(originName.getBytes("GBK"),"iso-8859-1");
}else{
originName = new String(originName.getBytes("GBK"),"iso-8859-1");
}
Boolean isSuccess = ftpClient.storeFile(originName,inputStream);//保存文件
if (!isSuccess){
throw new FtpException(originName+"---》上传失败!");
}
log.info("{}---》上传成功!",originName);
} catch (IOException e) {
log.error("{}---》上传失败!",originName);
throw new FtpException(originName+"上传失败!");
}finally {
if (null!=inputStream){
try {
inputStream.close();
} catch (IOException e) {
log.debug(e.getMessage());
}
} }

最新文章

  1. sqlalchemy(一)基本操作
  2. android自定义控件(7)-获取自定义ImageView的src属性
  3. Caffe学习系列(13):对训练好的模型进行fine-tune
  4. innerText在谷歌、火狐浏览器下的使用
  5. js 正则表达式中的惰性匹配
  6. Boost C++: 数据结构---tuple
  7. MongoDB 学习笔记(三)—— 修改器的使用
  8. MySQL通配符过滤
  9. 代码实现IMapcontrol当前视图输出为图片功能
  10. C字符数组及其应用
  11. UICollectionView设置item(cell)之间间距为0(紧挨在一起的效果)
  12. 【转】四步完成win7 ubuntu双系统安装(硬盘,无需光驱)
  13. Ansible@一个有效的配置管理工具--Ansible configure management--翻译(十二)
  14. setter设置器 gutter访问器
  15. android开源框架和开源项目(转)
  16. Servlet的学习(四)
  17. Caused by: org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 49; 前言中不允许有内容。
  18. jinja2.exceptions.TemplateNotFound: home/index.html
  19. PAT1129:Recommendation System
  20. spring中的mybatis的sqlSession是如何做到线程隔离的?

热门文章

  1. python内建模块——collections模块
  2. git cherry-pick的使用
  3. [CSP-S模拟测试]:chess(搜索+最短路)
  4. (转)GIS理论知识(三)之ArcGIS平台、SuperMap超图平台和开源平台
  5. Hive presto和hive时间格式转换
  6. day04—JavaScript之面向对象
  7. 测开之路七十二:性能测试工具之locust简介
  8. indy idhttpserver有关下载的两个问题
  9. Looper,Handler, MessageQueue
  10. DS-哈希表浅析