一、sftp工具类

  1. package com.ztesoft.iotcmp.util;
  2.  
  3. import com.jcraft.jsch.ChannelSftp;
  4. import com.jcraft.jsch.JSch;
  5. import com.jcraft.jsch.JSchException;
  6. import com.jcraft.jsch.Session;
  7. import com.jcraft.jsch.SftpException;
  8.  
  9. import java.io.*;
  10. import java.net.SocketException;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.Properties;
  14. import java.util.Vector;
  15. import java.util.zip.GZIPInputStream;
  16.  
  17. public class SftpUtil implements AutoCloseable {
  18. private Session session = null;
  19. private ChannelSftp channel = null;
  20.  
  21. private String userName = "bi";
  22. private String passWord = "bi";
  23. private String hostName = "10.40.197.41";
  24. private String port = "";
  25. private String workDir = "test/download";
  26.  
  27. public SftpUtil(String hostName, String port, String userName
  28. , String passWord, String workDir) throws IOException, JSchException {
  29. this.hostName = hostName;
  30. this.port = port;
  31. this.userName = userName;
  32. this.passWord = passWord;
  33. this.workDir = workDir;
  34. connectServer(hostName, Integer.parseInt(port), userName, passWord);
  35. }
  36.  
  37. /**
  38. * 连接sftp服务器
  39. *
  40. * @param serverIP 服务IP
  41. * @param port 端口
  42. * @param userName 用户名
  43. * @param password 密码
  44. * @throws SocketException SocketException
  45. * @throws IOException IOException
  46. * @throws JSchException JSchException
  47. */
  48. public void connectServer(String serverIP, int port, String userName, String password) throws JSchException {
  49. JSch jsch = new JSch();
  50. // 根据用户名,主机ip,端口获取一个Session对象
  51. session = jsch.getSession(userName, serverIP, port);
  52. // 设置密码
  53. session.setPassword(password);
  54. // 为Session对象设置properties
  55. Properties config = new Properties();
  56. config.put("StrictHostKeyChecking", "no");
  57. session.setConfig(config);
  58. // 通过Session建立链接
  59. session.connect();
  60. // 打开SFTP通道
  61. channel = (ChannelSftp) session.openChannel("sftp");
  62. // 建立SFTP通道的连接
  63. channel.connect();
  64.  
  65. }
  66.  
  67. /**
  68. * 自动关闭资源
  69. */
  70. public void close() {
  71. if (channel != null) {
  72. channel.disconnect();
  73. }
  74. if (session != null) {
  75. session.disconnect();
  76. }
  77. }
  78.  
  79. /**
  80. * @param path
  81. * @throws SftpException
  82. * @return获取目录下文件名称
  83. */
  84. public List<String> getDirFileList(String path) throws SftpException {
  85. List<String> list = new ArrayList<>();
  86. if (channel != null) {
  87. Vector vv = channel.ls(path);
  88. if (vv == null && vv.size() == 0) {
  89. return list;
  90. } else {
  91. Object[] aa = vv.toArray();
  92. for (int i = 0; i < aa.length; i++) {
  93. System.out.print(aa[i].toString());
  94. ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) aa[i];
  95. //获取文件名称
  96. String fileName = temp.getFilename();
  97. //判断文件名称是否为点
  98. if (!fileName.equals(".") && !fileName.equals("..")) {
  99. //判断文件是否为目录
  100. if (!temp.getAttrs().isDir()) {
  101. list.add(fileName);
  102. }
  103. }
  104. }
  105. }
  106. }
  107. return list;
  108. }
  109.  
  110. /**
  111. * 下载文件
  112. *
  113. * @param remotePathFile 远程文件
  114. * @param localPathFile 本地文件[绝对路径]
  115. * @throws SftpException SftpException
  116. * @throws IOException IOException
  117. */
  118. public void downloadFile(String remotePathFile, String localPathFile) throws SftpException, IOException {
  119. try (FileOutputStream os = new FileOutputStream(new File(localPathFile))) {
  120. if (channel == null)
  121. throw new IOException("sftp server not login");
  122. channel.get(remotePathFile, os);
  123. }
  124. }
  125.  
  126. /**
  127. * 下载文件
  128. *
  129. * @param downloadFile 下载的文件
  130. * @param saveFile 存在本地的路径
  131. */
  132. public void download(String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
  133. if (workDir != null && !"".equals(workDir)) {
  134. channel.cd(workDir);
  135. }
  136. File file = new File(saveFile);
  137. channel.get(downloadFile, new FileOutputStream(file));
  138. System.out.println("下载文件到"+saveFile+"目录完成!");
  139. }
  140.  
  141. /**
  142. * 下载文件
  143. *
  144. * @param downloadFile 下载的文件
  145. */
  146. public InputStream download(String downloadFile) {
  147. InputStream in = null;
  148. try {
  149. channel.cd(workDir);
  150. in = channel.get(downloadFile);
  151. } catch (Exception e) {
  152. e.printStackTrace();
  153. throw new RuntimeException(e);
  154. }
  155. return in;
  156. }
  157.  
  158. /**
  159. * 上传文件
  160. *
  161. * @param remoteFile 远程文件
  162. * @param localFile
  163. * @throws SftpException
  164. * @throws IOException
  165. */
  166. public void uploadFile(String remoteFile, String localFile) throws SftpException, IOException {
  167. try (FileInputStream in = new FileInputStream(new File(localFile))) {
  168. if (channel == null)
  169. throw new IOException("sftp server not login");
  170. channel.put(in, remoteFile);
  171. }
  172. }
  173.  
  174. /**
  175. * 下载流文件
  176. *
  177. * @param remoteFileName
  178. * @return
  179. * @throws SftpException
  180. * @throws IOException
  181. */
  182. public BufferedReader downloadGZFile(String remoteFileName) throws SftpException, IOException {
  183. BufferedReader returnValue = null;
  184.  
  185. //跳转目录
  186. Boolean state = openDir(this.workDir, channel);
  187.  
  188. //判断是否跳转到指定目录
  189. if (state) {
  190. InputStream in = new GZIPInputStream(channel.get(remoteFileName));
  191. if (in != null) {
  192. returnValue = new BufferedReader(new InputStreamReader(in));
  193. System.out.println("<----------- INFO: download " + this.workDir + "/" + remoteFileName + " from ftp : succeed! ----------->");
  194. } else {
  195. System.out.println("<----------- ERR : download " + this.workDir + "/" + remoteFileName + " from ftp : failed! ----------->");
  196. }
  197. }
  198.  
  199. return returnValue;
  200. }
  201.  
  202. /**
  203. * 跳转到指定的目录
  204. *
  205. * @param directory
  206. * @param sftp
  207. * @return
  208. */
  209. public static boolean openDir(String directory, ChannelSftp sftp) {
  210. try {
  211. sftp.cd(directory);
  212. return true;
  213. } catch (SftpException e) {
  214. return false;
  215. }
  216. }
  217.  
  218. public String getWorkDir() {
  219. return this.workDir;
  220. }
  221. }

二、文件处理思想流程

获取sftp连接

  1. SftpUtil sftpUtil = new SftpUtil(host,port,userName,passWord,dir);

根据路径获取文件列表

  1. List<String> fileList = sftpUtil.getDirFileList(sftpUtil.getWorkDir());
  2. if (fileList == null || fileList.isEmpty()) {
  3. throw new RuntimeException("没有文件要处理!");
  4. }

判断文件是否处理过

  1. boolean flag = SftpConfigUtil.checkFileIsDeal(fileName);//此处是根据表数据查询

未处理,进行处理过程

  1. if (!flag){
  2. BufferedReader reader = sftpUtil.downloadGZFile(fileName);//下载压缩文件并转化为流
  3.  
  4. List<TempPaymentDayAuditFileDTO> dataList = paseReader(reader, fileName);//解析文件字段,注意关闭文件流reader.close();
  5. tempPaymentDayAuditService.insertPaymentDayAudits(dataList);//插入数据库
  6. SftpConfigUtil.insertFileIsDeal(fileName);//插入文件已处理标记到数据表中
  7. }

关闭sftp连接

  1. sftpUtil.close();

三、ftp工具类

  1. package com.ztesoft.iotcmp.util;
  2.  
  3. import org.apache.commons.io.IOUtils;
  4. import org.apache.commons.net.ftp.FTP;
  5. import org.apache.commons.net.ftp.FTPClient;
  6. import org.apache.commons.net.ftp.FTPFile;
  7. import org.apache.commons.net.ftp.FTPReply;
  8.  
  9. import java.io.*;
  10. import java.util.ArrayList;
  11. import java.util.Iterator;
  12. import java.util.List;
  13. import java.util.zip.GZIPInputStream;
  14.  
  15. /**
  16. * Ftp操作工具类
  17. *
  18. * @author easonwu
  19. *
  20. */
  21. public class FtpUtil {
  22.  
  23. private String userName = "bi";
  24. private String passWord = "bi";
  25. private String hostName = "10.40.197.41" ;
  26. private String port = "" ;
  27. private String workDir = "test/download" ;
  28. private FTPClient ftpClient = new FTPClient();
  29.  
  30. public FtpUtil() throws IOException {
  31. initailCheck() ;
  32. }
  33.  
  34. public FtpUtil(String hostName , String port , String userName
  35. , String passWord , String workDir) throws IOException {
  36. this.hostName = hostName ;
  37. this.port = port ;
  38. this.userName = userName ;
  39. this.passWord = passWord ;
  40. this.workDir = workDir ;
  41. initailCheck() ;
  42. }
  43.  
  44. private void initailCheck() throws IOException {
  45. connectToServer();
  46. if( this.workDir != null && !"".endsWith(this.workDir )){
  47. checkPathExist(this.workDir);
  48. }
  49. closeConnect();
  50. }
  51.  
  52. /**
  53. * 查找指定目录是否存在
  54. * @param filePath 要查找的目录
  55. * @return boolean:存在:true,不存在:false
  56. * @throws IOException
  57. */
  58. private boolean checkPathExist(String filePath) throws IOException {
  59. boolean existFlag = false;
  60. try {
  61. if (!ftpClient.changeWorkingDirectory(filePath)) {
  62. ftpClient.makeDirectory(filePath);
  63. }
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. return existFlag;
  68. }
  69.  
  70. /**
  71. * 连接到ftp服务器
  72. */
  73. private void connectToServer() throws IOException{
  74. if(!ftpClient.isConnected()){
  75. int reply;
  76. try{
  77. ftpClient = new FTPClient();
  78. ftpClient.enterLocalPassiveMode();
  79.  
  80. if(this.port == null || "".equals(this.port)){
  81. ftpClient.connect(this.hostName);
  82. }
  83. else{
  84. ftpClient.connect(this.hostName, Integer.parseInt(this.port));
  85. }
  86.  
  87. ftpClient.login(userName, passWord);
  88. reply = ftpClient.getReplyCode();
  89.  
  90. if(!FTPReply.isPositiveCompletion(reply)){
  91. ftpClient.disconnect();
  92. System.err.println("FTP server refused connection.");
  93. }
  94. }
  95. catch(IOException e){
  96. // System.err.println("登录ftp服务器【" + this.hostName + "】失败");
  97. e.printStackTrace();
  98. throw new IOException("登录ftp服务器【" + this.hostName + "】失败");
  99. }
  100. }
  101. }
  102.  
  103. /**
  104. * 关闭连接
  105. */
  106. private void closeConnect() {
  107. try {
  108. if (ftpClient != null) {
  109. ftpClient.logout();
  110. ftpClient.disconnect();
  111. }
  112. } catch (Exception e) {
  113. e.printStackTrace();
  114. }
  115. }
  116.  
  117. /**
  118. * 转码[GBK -> ISO-8859-1]
  119. * 不同的平台需要不同的转码
  120. * @param obj
  121. * @return
  122. */
  123. private static String gbkToIso8859(Object obj) {
  124. try {
  125. if (obj == null)
  126. return "";
  127. else
  128. return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
  129. } catch (Exception e) {
  130. return "";
  131. }
  132. }
  133.  
  134. /**
  135. * 转码[ISO-8859-1 -> GBK]
  136. * 不同的平台需要不同的转码
  137. * @param obj
  138. * @return
  139. */
  140. private static String iso8859ToGbk(Object obj) {
  141. try {
  142. if (obj == null)
  143. return "";
  144. else
  145. return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
  146. } catch (Exception e) {
  147. return "";
  148. }
  149. }
  150.  
  151. /**
  152. * 设置传输文件的类型[文本文件或者二进制文件]
  153. * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
  154. */
  155. private void setFileType(int fileType) {
  156. try {
  157. ftpClient.setFileType(fileType);
  158. } catch (Exception e) {
  159. e.printStackTrace();
  160. }
  161. }
  162.  
  163. private void changeDir(String filePath) throws IOException {
  164. // 跳转到指定的文件目录
  165. if (filePath != null && !filePath.equals("")) {
  166. if (filePath.indexOf("/") != -1) {
  167. int index = 0;
  168. while ((index = filePath.indexOf("/")) != -1) {
  169. System.out.println("P:"+ filePath.substring(0,
  170. index)) ;
  171. ftpClient.changeWorkingDirectory(filePath.substring(0,
  172. index));
  173.  
  174. filePath = filePath.substring(index + 1, filePath.length());
  175. }
  176. if (!filePath.equals("") && !"/".equals(filePath)) {
  177. ftpClient.changeWorkingDirectory(filePath);
  178. }
  179. } else {
  180. ftpClient.changeWorkingDirectory(filePath);
  181. }
  182. }
  183. }
  184. /**
  185. * check file
  186. * @param filePath
  187. * @param fileName
  188. * @return
  189. * @throws IOException
  190. */
  191. private boolean checkFileExist(String filePath, String fileName)
  192. throws IOException {
  193. boolean existFlag = false;
  194. changeDir( filePath ) ;
  195. String[] fileNames = ftpClient.listNames();
  196. if (fileNames != null && fileNames.length > 0) {
  197. for (int i = 0; i < fileNames.length; i++) {
  198. System.out.println("File:" + iso8859ToGbk(fileNames[i])) ;
  199. if (fileNames[i] != null
  200. && iso8859ToGbk(fileNames[i]).equals(fileName)) {
  201. existFlag = true;
  202. break;
  203. }
  204. }
  205. }
  206. ftpClient.changeToParentDirectory();
  207. return existFlag;
  208. }
  209.  
  210. /**
  211. * download ftp file as inputstream
  212. * @param remoteFileName
  213. * @return
  214. * @throws IOException
  215. */
  216. public InputStream downloadFile(
  217. String remoteFileName) throws IOException {
  218. InputStream returnValue = null;
  219. //下载文件
  220. BufferedOutputStream buffOut = null;
  221. try {
  222. //连接ftp服务器
  223. connectToServer();
  224. if (!checkFileExist(this.workDir, remoteFileName)) {
  225. System.out.println("<----------- ERR : file " + this.workDir + "/" + remoteFileName+ " does not exist, download failed!----------->");
  226. return null;
  227. } else {
  228. changeDir( this.workDir ) ;
  229. String[] fileNames = ftpClient.listNames();
  230.  
  231. //设置传输二进制文件
  232. setFileType(FTP.BINARY_FILE_TYPE);
  233. //获得服务器文件
  234. InputStream in = ftpClient.retrieveFileStream(remoteFileName);
  235. //输出操作结果信息
  236. if (in != null) {
  237. returnValue = new ByteArrayInputStream(IOUtils.toByteArray(in));
  238. in.close();
  239. System.out.println("<----------- INFO: download "+ this.workDir + "/" + remoteFileName+ " from ftp : succeed! ----------->");
  240. } else {
  241. System.out.println("<----------- ERR : download "+ this.workDir + "/" + remoteFileName+ " from ftp : failed! ----------->");
  242. }
  243. }
  244. //关闭连接
  245. closeConnect();
  246. } catch (Exception e) {
  247. e.printStackTrace();
  248. returnValue = null;
  249. //输出操作结果信息
  250. System.out.println("<----------- ERR : download " + this.workDir + "/" + remoteFileName+ " from ftp : failed! ----------->");
  251. } finally {
  252. try {
  253. if (ftpClient.isConnected()) {
  254. closeConnect();
  255. }
  256. } catch (Exception e) {
  257. e.printStackTrace();
  258. }
  259. }
  260. return returnValue;
  261. }
  262.  
  263. /**
  264. *
  265. * @param remoteFilePath
  266. * @param remoteFileName
  267. * @param localFileName
  268. * @return
  269. * @throws IOException
  270. */
  271. public boolean downloadFile(String remoteFilePath,
  272. String remoteFileName, String localFileName) throws IOException {
  273. boolean returnValue = false;
  274. //下载文件
  275. BufferedOutputStream buffOut = null;
  276. try {
  277. //连接ftp服务器
  278. connectToServer();
  279. File localFile = new File(localFileName.substring(0, localFileName
  280. .lastIndexOf("/")));
  281. if (!localFile.exists()) {
  282. localFile.mkdirs();
  283. }
  284. if (!checkFileExist(remoteFilePath, remoteFileName)) {
  285. System.out.println("<----------- ERR : file " + remoteFilePath + "/" + remoteFileName+ " does not exist, download failed!----------->");
  286. return false;
  287. } else {
  288. changeDir( remoteFilePath ) ;
  289. String[] fileNames = ftpClient.listNames();
  290.  
  291. //设置传输二进制文件
  292. setFileType(FTP.BINARY_FILE_TYPE);
  293. //获得服务器文件
  294. buffOut = new BufferedOutputStream(new FileOutputStream(
  295. localFileName));
  296. returnValue = ftpClient.retrieveFile(
  297. remoteFileName, buffOut);
  298. //输出操作结果信息
  299. if (returnValue) {
  300. System.out.println("<----------- INFO: download "+ remoteFilePath + "/" + remoteFileName+ " from ftp : succeed! ----------->");
  301. } else {
  302. System.out.println("<----------- ERR : download "+ remoteFilePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
  303. }
  304. }
  305. //关闭连接
  306. closeConnect();
  307. } catch (Exception e) {
  308. e.printStackTrace();
  309. returnValue = false;
  310. //输出操作结果信息
  311. System.out.println("<----------- ERR : download " + remoteFilePath+ "/" + remoteFileName+ " from ftp : failed! ----------->");
  312. } finally {
  313. try {
  314. if (buffOut != null) {
  315. buffOut.close();
  316. }
  317. if (ftpClient.isConnected()) {
  318. closeConnect();
  319. }
  320. } catch (Exception e) {
  321. e.printStackTrace();
  322. }
  323. }
  324. return returnValue;
  325. }
  326.  
  327. /**
  328. *
  329. * @param remoteFileNameList
  330. * @return
  331. * @throws IOException
  332. */
  333. public List batchDownloadFile(
  334. List remoteFileNameList) throws IOException {
  335. InputStream resultIs = null ;
  336. List inputStreamList = null ;
  337. String remoteFileName = null ;
  338.  
  339. if( remoteFileNameList == null ||remoteFileNameList.isEmpty() ) return null ;
  340.  
  341. inputStreamList = new ArrayList() ;
  342. for( Iterator it = remoteFileNameList.iterator() ; it.hasNext() ; ) {
  343. remoteFileName = (String)it.next() ;
  344. resultIs = this.downloadFile(remoteFileName);
  345. if (resultIs != null ) {
  346. inputStreamList.add(resultIs) ;
  347. }
  348. }
  349. return inputStreamList;
  350. }
  351.  
  352. /**
  353. * 删除服务器上文件
  354. *
  355. * @param fileDir
  356. * 文件路径
  357. * @param fileName
  358. * 文件名称
  359. * @throws IOException
  360. */
  361. public boolean delFile(String fileDir, String fileName) throws IOException {
  362. boolean returnValue = false;
  363. try {
  364. //连接ftp服务器
  365. connectToServer();
  366. //跳转到指定的文件目录
  367. if (fileDir != null) {
  368. if (fileDir.indexOf("/") != -1) {
  369. int index = 0;
  370. while ((index = fileDir.indexOf("/")) != -1) {
  371. ftpClient.changeWorkingDirectory(fileDir.substring(0,
  372. index));
  373. fileDir = fileDir
  374. .substring(index + 1, fileDir.length());
  375. }
  376. if (!fileDir.equals("")) {
  377. ftpClient.changeWorkingDirectory(fileDir);
  378. }
  379. } else {
  380. ftpClient.changeWorkingDirectory(fileDir);
  381. }
  382. }
  383. //设置传输二进制文件
  384. setFileType(FTP.BINARY_FILE_TYPE);
  385. //获得服务器文件
  386. returnValue = ftpClient.deleteFile(fileName);
  387. //关闭连接
  388. closeConnect();
  389. //输出操作结果信息
  390. if (returnValue) {
  391. System.out.println("<----------- INFO: delete " + fileDir + "/"
  392. + fileName + " at ftp:succeed! ----------->");
  393. } else {
  394. System.out.println("<----------- ERR : delete " + fileDir + "/"
  395. + fileName + " at ftp:failed! ----------->");
  396. }
  397. } catch (Exception e) {
  398. e.printStackTrace();
  399. returnValue = false;
  400. //输出操作结果信息
  401. System.out.println("<----------- ERR : delete " + fileDir + "/"
  402. + fileName + " at ftp:failed! ----------->");
  403. } finally {
  404. try {
  405. if (ftpClient.isConnected()) {
  406. closeConnect();
  407. }
  408. } catch (Exception e) {
  409. e.printStackTrace();
  410. }
  411. }
  412. return returnValue;
  413. }
  414.  
  415. /**
  416. * upload file to ftp
  417. * @param uploadFile
  418. * @param fileName
  419. * @return
  420. * @throws IOException
  421. */
  422. public boolean uploadFile(String uploadFile , String fileName ) throws IOException{
  423. if(uploadFile == null || "".equals(uploadFile.trim())){
  424. System.out.println("<----------- ERR : uploadFile:" + uploadFile
  425. + " is null , upload failed! ----------->");
  426. return false ;
  427. }
  428. return this.uploadFile(new File(uploadFile) , fileName ) ;
  429. }
  430.  
  431. /**
  432. * batch upload files
  433. * @param uploadFileList
  434. * @return
  435. * @throws IOException
  436. */
  437. public boolean batchUploadFile(List uploadFileList ) throws IOException{
  438. if(uploadFileList == null || uploadFileList.isEmpty()){
  439. System.out.println("<----------- ERR : batchUploadFile failed! because the file list is empty ! ----------->");
  440. return false ;
  441. }
  442.  
  443. for( Iterator it = uploadFileList.iterator() ; it.hasNext() ;){
  444. File uploadFile = (File)it.next() ;
  445. if( !uploadFile(uploadFile , uploadFile.getName() ) ){
  446. System.out.println("<----------- ERR : upload file【"+uploadFile.getName()+"】 failed! ----------->") ;
  447. return false ;
  448. }
  449. }
  450. return true ;
  451. }
  452.  
  453. /**
  454. * upload file to ftp
  455. * @param uploadFile
  456. * @param fileName
  457. * @return
  458. * @throws IOException
  459. */
  460. public boolean uploadFile(File uploadFile, String fileName)
  461. throws IOException {
  462. if (!uploadFile.exists()) {
  463. System.out.println("<----------- ERR : an named " + fileName
  464. + " not exist, upload failed! ----------->");
  465. return false;
  466. }
  467. return this.uploadFile(new FileInputStream(uploadFile) , fileName ) ;
  468. }
  469.  
  470. /**
  471. * upload file to ftp
  472. * @param is
  473. * @param fileName
  474. * @return
  475. * @throws IOException
  476. */
  477. public boolean uploadFile(InputStream is , String fileName ) throws IOException {
  478. boolean returnValue = false;
  479. // 上传文件
  480. BufferedInputStream buffIn = null;
  481. try {
  482.  
  483. // 建立连接
  484. connectToServer();
  485. // 设置传输二进制文件
  486. setFileType(FTP.BINARY_FILE_TYPE);
  487. // 获得文件
  488. buffIn = new BufferedInputStream(is);
  489. // 上传文件到ftp
  490. ftpClient.enterLocalPassiveMode();
  491. returnValue = ftpClient.storeFile(gbkToIso8859(this.workDir + "/"
  492. + fileName), buffIn);
  493. // 输出操作结果信息
  494. if (returnValue) {
  495. System.out.println("<----------- INFO: upload file to ftp : succeed! ----------->");
  496. } else {
  497. System.out.println("<----------- ERR : upload file to ftp : failed! ----------->");
  498. }
  499. // 关闭连接
  500. closeConnect();
  501.  
  502. } catch (Exception e) {
  503. e.printStackTrace();
  504. returnValue = false;
  505. System.out.println("<----------- ERR : upload file to ftp : failed! ----------->");
  506. } finally {
  507. try {
  508. if (buffIn != null) {
  509. buffIn.close();
  510. }
  511. if (ftpClient.isConnected()) {
  512. closeConnect();
  513. }
  514. } catch (Exception e) {
  515. e.printStackTrace();
  516. }
  517. }
  518. return returnValue ;
  519. }
  520.  
  521. public boolean changeDirectory(String path) throws IOException {
  522. return ftpClient.changeWorkingDirectory(path);
  523. }
  524. public boolean createDirectory(String pathName) throws IOException {
  525. return ftpClient.makeDirectory(pathName);
  526. }
  527. public boolean removeDirectory(String path) throws IOException {
  528. return ftpClient.removeDirectory(path);
  529. }
  530. // delete all subDirectory and files.
  531. public boolean removeDirectory(String path, boolean isAll)
  532. throws IOException {
  533.  
  534. if (!isAll) {
  535. return removeDirectory(path);
  536. }
  537.  
  538. FTPFile[] ftpFileArr = ftpClient.listFiles(path);
  539. if (ftpFileArr == null || ftpFileArr.length == 0) {
  540. return removeDirectory(path);
  541. }
  542. //
  543. for (int i=ftpFileArr.length ; i>0 ; i-- ) {
  544. FTPFile ftpFile = ftpFileArr[i-1] ;
  545. String name = ftpFile.getName();
  546. if (ftpFile.isDirectory()) {
  547. System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");
  548. removeDirectory(path + "/" + name, true);
  549. } else if (ftpFile.isFile()) {
  550. System.out.println("* [sF]Delete file ["+path + "/" + name+"]");
  551. deleteFile(path + "/" + name);
  552. }
  553. // else if (ftpFile.isSymbolicLink()) {
  554. //
  555. // } else if (ftpFile.isUnknown()) {
  556. //
  557. // }
  558. }
  559. return ftpClient.removeDirectory(path);
  560. }
  561.  
  562. public boolean deleteFile(String pathName) throws IOException {
  563. return ftpClient.deleteFile(pathName);
  564. }
  565.  
  566. public List getFileList(String path) throws IOException {
  567. FTPFile[] ftpFiles= ftpClient.listFiles(path);
  568.  
  569. List retList = new ArrayList();
  570. if (ftpFiles == null || ftpFiles.length == 0) {
  571. return retList;
  572. }
  573. for (int i=ftpFiles.length ; i>0 ; i-- ) {
  574. FTPFile ftpFile = ftpFiles[i-1] ;
  575. if (ftpFile.isFile()) {
  576. retList.add(ftpFile.getName());
  577. }
  578. }
  579.  
  580. return retList;
  581. }
  582.  
  583. private void changeWordDir(String wd) throws IOException{
  584. if(wd != null && wd != ""){
  585. if(!ftpClient.changeWorkingDirectory(wd)){
  586. ftpClient.makeDirectory(wd);
  587. ftpClient.changeWorkingDirectory(wd);
  588. }
  589. }
  590. }
  591.  
  592. /**
  593. * 上传文件到服务器上
  594. * @param is 文件流
  595. * @param filepath FTP服务器上文件路径
  596. * @param filename 文件名称
  597. * @return
  598. * @throws Exception
  599. */
  600. public boolean uploadFile(InputStream is,String filepath,String filename) throws Exception{
  601. if(!ftpClient.isConnected()){
  602. connectToServer();
  603. }
  604. changeWordDir(this.workDir);
  605. changeWordDir(filepath);
  606. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  607. ftpClient.enterLocalPassiveMode();
  608. boolean isSuccess = ftpClient.storeFile(filename, is);
  609. if(isSuccess){
  610. System.out.println("<-- INFO:upload "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
  611. }else{
  612. System.out.println("<-- INFO:upload "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
  613. }
  614. is.close();
  615. closeConnect();
  616. return isSuccess;
  617. }
  618.  
  619. /**
  620. * 从FTP服务器上下载文件
  621. * @param filepath FTP服务器文件路径
  622. * @param filename 文件名称
  623. * @param localPath 本机文件路径
  624. * @return
  625. * @throws IOException
  626. */
  627. public boolean downLoadFile(String filepath,String filename,String localPath) throws IOException{
  628. if(!ftpClient.isConnected()){
  629. connectToServer();
  630. }
  631. changeWordDir(this.workDir);
  632. changeWordDir(filepath);
  633. if(ftpClient.listNames(filename).length > 0){
  634. setFileType(FTP.BINARY_FILE_TYPE);
  635. File localFile = new File(localPath+"/"+filename);
  636. OutputStream os = new FileOutputStream(localFile);
  637. boolean isSuccess = ftpClient.retrieveFile(filename, os);
  638. if(isSuccess){
  639. System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
  640. }else{
  641. System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
  642. }
  643. os.close();
  644. closeConnect();
  645. return isSuccess;
  646. }else{
  647. System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: failed, file is not exist -->");
  648. }
  649. closeConnect();
  650. return false;
  651. }
  652.  
  653. /**
  654. * 删除FTP服务器上的文件
  655. * @param filepath 文件路径
  656. * @param filename 文件名称
  657. * @throws IOException
  658. */
  659. public boolean deleteFile(String filepath,String filename) throws IOException{
  660. if(!ftpClient.isConnected()){
  661. connectToServer();
  662. }
  663. changeWordDir(this.workDir);
  664. changeWordDir(filepath);
  665. boolean isSuccess = false;
  666. if(ftpClient.listNames(filename).length > 0){
  667. isSuccess = ftpClient.deleteFile(filename);
  668. if(isSuccess){
  669. System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
  670. }else{
  671. System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
  672. }
  673. }else{
  674. System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: failed, file is not exist -->");
  675. }
  676. closeConnect();
  677. return isSuccess;
  678. }
  679.  
  680. /**
  681. * download ftp .gz file as BufferedReader
  682. * @param remoteFileName
  683. * @return
  684. * @throws IOException
  685. */
  686. public BufferedReader downloadGZFile(
  687. String remoteFileName, String filePath) throws IOException {
  688. BufferedReader returnValue = null;
  689. //下载文件
  690. BufferedOutputStream buffOut = null;
  691. try {
  692. //连接ftp服务器
  693. connectToServer();
  694. if (!checkFileExist(filePath, remoteFileName)) {
  695. System.out.println("<----------- ERR : file " + filePath + "/" + remoteFileName+ " does not exist, download failed!----------->");
  696. return null;
  697. } else {
  698. changeDir( filePath ) ;
  699. String[] fileNames = ftpClient.listNames();
  700.  
  701. //设置传输二进制文件
  702. setFileType(FTP.BINARY_FILE_TYPE);
  703. //获得服务器文件
  704. InputStream in = new GZIPInputStream(ftpClient.retrieveFileStream(remoteFileName));
  705. //输出操作结果信息
  706. if (in != null) {
  707. returnValue = new BufferedReader(new InputStreamReader(in));
  708. in.close();
  709. System.out.println("<----------- INFO: download "+ filePath + "/" + remoteFileName+ " from ftp : succeed! ----------->");
  710. } else {
  711. System.out.println("<----------- ERR : download "+ filePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
  712. }
  713. }
  714. //关闭连接
  715. closeConnect();
  716. } catch (Exception e) {
  717. e.printStackTrace();
  718. returnValue = null;
  719. //输出操作结果信息
  720. System.out.println("<----------- ERR : download " + filePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
  721. } finally {
  722. try {
  723. if (ftpClient.isConnected()) {
  724. closeConnect();
  725. }
  726. } catch (Exception e) {
  727. e.printStackTrace();
  728. }
  729. }
  730. return returnValue;
  731. }
  732.  
  733. public String getWorkDir()
  734. {
  735. return this.workDir;
  736. }
  737. }
  1. reader.close();

sftp,ftp文件下载的更多相关文章

  1. Sublime text3 连接sftp/ftp(远程服务器)

    1.按下Ctrl + Shift + P调出命令面板2.在输入框中输入Sftp,按回车下载3.建一个新的文件夹放到左边的项目栏中4.右击文件夹,选中SFTP/FTP,点击Map to Remote5. ...

  2. Sublime Text下使用SFTP/FTP插件

    一.前言 本文主要记录了Sublime Text编辑器下的SFTP/FTP的安装使用,方便linux和windows下的文件编辑,只是简单的记录,有不足之处,还望指教. 二.Linux和windows ...

  3. sftp ftp文件同步方案

    sftp ftp文件同步方案 1. 需求 1.1实现网关服务器的ftp服务器的/batchFileRequest目录下文件向徽商所使用的sftp服务器的/batchFileRequest目录同步文件 ...

  4. Gradle之FTP文件下载

    Gradle之FTP文件下载 1.背景 项目上需要使用本地web,所以我们直接将web直接放入assets资源文件夹下.但是随着开发进行web包越来越大:所以我们想着从版本库里面去掉web将其忽略掉, ...

  5. 【转】JSch - Java实现的SFTP(文件下载详解篇)

    上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等.   同样,JSch的文件下载也支持三种传输模式:OVERWRI ...

  6. JSch - Java实现的SFTP(文件下载详解篇)

    上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等. 同样,JSch的文件下载也支持三种传输模式:OVERWRITE ...

  7. JSch - Java实现的SFTP(文件下载详解篇)(转)

    上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等.   同样,JSch的文件下载也支持三种传输模式:OVERWRI ...

  8. java实现FTP文件下载

    package com.vingsoft.util;/*** @author 作者:dujj* @version 创建时间:2020年1月13日 下午5:53:39*/import java.io.F ...

  9. 【Web】Sublime Text 3 连接sftp/ftp(远程服务器)

    在 Win 下常用 Xftp 软件来和远程服务传递文件,但是要是在项目开发的时候频繁的将远程文件拖到本地编辑然后再传回远程服务器,那真是麻烦无比,但是Sublime中SFTP插件,它让这世界美好了许多 ...

随机推荐

  1. python-flask模块注入(SSTI)

    前言: 第一次遇到python模块注入是做ctf的时候,当时并没有搞懂原理所在,看了网上的资料,这里做一个笔记. flask基础: 先看一段python代码: from flask import fl ...

  2. Window Api 通过账号密码访问共享文件夹

    using System; using System.Runtime.InteropServices; namespace PushGCodeService { public class Shared ...

  3. 请求筛选模块被配置为拒绝包含双重转义序列的请求(.net core程序的‘web.config’调整)

    之前项目有一个静态文件特殊字符转义的报错(+变为 %2B),老是显示404  请求筛选模块被配置为拒绝包含双重转义序列的请求  .网上的大多数解决方案都是一下: https://www.cnblogs ...

  4. JavaScript DOM–事件操作

    事件 注册事件 给元素添加事件,为注册事件或者绑定事件 注册事件两种方式 传统方式 监听事件方式 事件监听 addEventListener() 事件监听 (IE9以上) eventTarget.ad ...

  5. ImportError: libzmq.so.5 报错

    https://pkgs.org/download/libzmq.so.5()(64bit) # rpm -ivh zeromq-4.1.4-6.el7.x86_64.rpm

  6. css代码实现switch开关滑动

    效果预览: 代码如下: <style> #toggle-button{ display: none; } .button-label{ position: relative; displa ...

  7. 在RYU中实现交换机的功能

    首先源码,解析部分如下,同时可以参考RYU_BOOK上的解释说明  原文链接参考:https://blog.csdn.net/qq_34099967/article/details/89047741 ...

  8. [AH2017/HNOI2017] 影魔 - 线段树

    #include<bits/stdc++.h> #define maxn 200010 using namespace std; int a[maxn],st[maxn][2],top,L ...

  9. ActiveMQ注意事项

    1.消费者在消费数据的过程当中报错,那么就会自动重试        2.如果消费者报错,会自动重试,但是数据已经真实拿到,可能会造成重复消费,幂等性问题            思路,每一次监听到数据后 ...

  10. java学习笔记之集合—ArrayList源码解析

    1.ArrayList简介 ArrayList是一个数组队列,与java中的数组的容量固定不同,它可以动态的实现容量的增涨.所以ArrayList也叫动态数组.当我们知道有多少个数据元素的时候,我们用 ...