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