FtpUtil.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package com.uas.util;
  2. import com.jcraft.jsch.JSchException;
  3. import org.apache.commons.net.ftp.FTPClient;
  4. import org.apache.commons.net.ftp.FTPFile;
  5. import org.apache.commons.net.ftp.FTPReply;
  6. import java.io.*;
  7. import java.util.*;
  8. public class FtpUtil {
  9. /**
  10. * 连接到ftp站点,判断是否可以连接
  11. * @param path 要连接到的目录
  12. * @param addr 站点地址
  13. * @param port 端口
  14. * @param username 用户名
  15. * @param password 密码
  16. * @return
  17. * @throws Exception
  18. */
  19. public static boolean connect(String path, String addr, int port, String username,
  20. String password) {
  21. boolean result = false;
  22. try {
  23. FTPClient ftp = new FTPClient();
  24. int reply;
  25. ftp.connect(addr, port);
  26. ftp.login(username, password);
  27. ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
  28. reply = ftp.getReplyCode();
  29. if (!FTPReply.isPositiveCompletion(reply)) {
  30. ftp.disconnect();
  31. return result;
  32. }
  33. ftp.changeWorkingDirectory(path);
  34. result = true;
  35. return result;
  36. }catch (Exception e){
  37. SFTPUtil sftp = new SFTPUtil(username, password, addr, port);
  38. try {
  39. sftp.login();
  40. result = true;
  41. } catch (JSchException e1) {
  42. e1.printStackTrace();
  43. }
  44. return result;
  45. }
  46. }
  47. /**
  48. * 获取ftp连接,该连接指向ftp配置中的downloadpath文件夹
  49. * @param map 包含ftp连接配置的map
  50. */
  51. public static FTPClient connect(Map<String,Object> map) throws Exception {
  52. return connect(map,map.get("downloadpath").toString());
  53. }
  54. /**
  55. * 获取ftp连接,该连接指向ftp配置中的downloadpath文件夹
  56. * @param map 包含ftp连接配置的map
  57. */
  58. public static FTPClient connect(Map<String,Object> map,String path){
  59. FTPClient ftp = null;
  60. String addr = null;
  61. try{
  62. addr = map.get("ip").toString();
  63. int port = Integer.parseInt(map.get("port").toString());
  64. String username = map.get("user").toString();
  65. String password = map.get("password").toString();
  66. ftp = new FTPClient();
  67. int reply;
  68. ftp.setDefaultTimeout(30*1000);
  69. ftp.setConnectTimeout(30*1000);
  70. ftp.setDataTimeout(30*1000);
  71. //设置ftp为被动模式,解决有时候ftp会卡住问题
  72. ftp.enterLocalPassiveMode();
  73. ftp.connect(addr, port);
  74. if(!ftp.login(username, password)){
  75. return null;
  76. }
  77. ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
  78. reply = ftp.getReplyCode();
  79. if (!FTPReply.isPositiveCompletion(reply)) {
  80. ftp.disconnect();
  81. return null;
  82. }
  83. ftp.changeWorkingDirectory(path);
  84. return ftp;
  85. }catch(Exception e){
  86. BaseUtil.getLogger().error("ip:" + addr + e.toString());
  87. e.printStackTrace();
  88. return null;
  89. }
  90. }
  91. /**
  92. * 上传文件
  93. * @param ftpClient 已连接的ftp客户端
  94. * @param pathname 路径
  95. * @param file 待上传的文件
  96. * @return 上传结果
  97. */
  98. public static boolean uploadFile(FTPClient ftpClient, String pathname, File file) {
  99. boolean flag = false;
  100. ftpClient.setControlEncoding("UTF-8");
  101. try {
  102. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  103. boolean change = ftpClient.changeWorkingDirectory("/"+pathname);
  104. if(!change){
  105. BaseUtil.getLogger().info("change to " + pathname + " fail");
  106. return false;
  107. }
  108. InputStream inputStream = new FileInputStream(file);
  109. ftpClient.enterLocalPassiveMode();
  110. ftpClient.storeFile(file.getName(), inputStream);
  111. inputStream.close();
  112. //ftpClient.logout();
  113. flag = true;
  114. } catch (Exception e) {
  115. e.printStackTrace();
  116. BaseUtil.getLogger().error(e.toString());
  117. if (ftpClient.isConnected()) {
  118. try {
  119. ftpClient.disconnect();
  120. } catch (IOException e1) {
  121. BaseUtil.getLogger().error(e1.toString());
  122. e1.printStackTrace();
  123. }
  124. }
  125. }
  126. return flag;
  127. }
  128. /**
  129. * 删除后关闭ftp连接
  130. * @param ftpClient
  131. * @param filename 要删除的文件名
  132. * @return 删除结果
  133. */
  134. public static boolean deleteFile(FTPClient ftpClient,String filename) {
  135. boolean flag = false;
  136. try {
  137. ftpClient.dele(filename);
  138. flag = true;
  139. } catch (Exception e) {
  140. BaseUtil.getLogger().error(e.toString());
  141. e.printStackTrace();
  142. }
  143. return flag;
  144. }
  145. /**
  146. *
  147. * @param ftpClient
  148. * fileType 需要下载的文件类型
  149. * @return 获取连接到的ftp站点下的文件夹所有文件
  150. */
  151. public static List<File> downloadAllFileByType(FTPClient ftpClient,String fileType) {
  152. List<File> files = new ArrayList<File>();
  153. try {
  154. ftpClient.enterLocalPassiveMode();
  155. FTPFile[] ftpFiles = ftpClient.listFiles();
  156. if (ftpFiles != null && ftpFiles.length > 0) {
  157. ArrayList<FTPFile> list = new ArrayList<FTPFile>(Arrays.asList(ftpFiles));
  158. Collections.sort(list, new Comparator<FTPFile>() {
  159. @Override
  160. public int compare(FTPFile o1, FTPFile o2) {
  161. long time = o1.getTimestamp().getTime().getTime();
  162. long time1 = o2.getTimestamp().getTime().getTime();
  163. if (time > time1) {
  164. return 1;
  165. }
  166. if (time == time1) {
  167. return 0;
  168. }
  169. return -1;
  170. }
  171. });
  172. for (FTPFile file : list) {
  173. if (file.getName().toUpperCase().endsWith("." + fileType)) {
  174. File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
  175. OutputStream os = new FileOutputStream(localFile);
  176. ftpClient.retrieveFile(file.getName(), os);
  177. os.close();
  178. files.add(localFile);
  179. }
  180. }
  181. }
  182. } catch (Exception e) {
  183. BaseUtil.getLogger().error(e.toString());
  184. e.printStackTrace();
  185. }
  186. return files;
  187. }
  188. /**
  189. *
  190. * @param ftpClient
  191. * fileType 需要下载的文件类型
  192. * @return 获取连接到的ftp站点下的文件夹所有文件
  193. */
  194. public static List<File> downloadAllFileByType(FTPClient ftpClient) {
  195. List<File> files = new ArrayList<File>();
  196. try {
  197. ftpClient.enterLocalPassiveMode();
  198. FTPFile[] ftpFiles = ftpClient.listFiles();
  199. for (FTPFile file : ftpFiles) {
  200. if(!".".equals(file.getName()) && !"..".equals(file.getName())&& !"bak".equals(file.getName())){
  201. File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
  202. OutputStream os = new FileOutputStream(localFile);
  203. ftpClient.retrieveFile(file.getName(), os);
  204. os.close();
  205. files.add(localFile);
  206. }
  207. }
  208. } catch (Exception e) {
  209. BaseUtil.getLogger().error(e.toString());
  210. e.printStackTrace();
  211. }
  212. return files;
  213. }
  214. /**
  215. * 关闭ftp连接
  216. * @param ftpClient
  217. */
  218. public static void closeFtpClient(FTPClient ftpClient){
  219. if (ftpClient.isConnected()) {
  220. try {
  221. ftpClient.logout();
  222. } catch (IOException e) {
  223. BaseUtil.getLogger().error(e.toString());
  224. }
  225. }
  226. }
  227. /**
  228. *
  229. * @param ftpClient
  230. * @return 获取连接到的ftp站点下的文件夹所有文件
  231. */
  232. public static List<File> downloadFileByDirectory(FTPClient ftpClient,String directory,String fileType) {
  233. List<File> files = new ArrayList<File>();
  234. try {
  235. ftpClient.enterLocalPassiveMode();
  236. ftpClient.changeWorkingDirectory("/" + directory);// 转移到FTP服务器目录
  237. FTPFile[] ftpFiles = ftpClient.listFiles();
  238. if (ftpFiles != null && ftpFiles.length > 0) {
  239. ArrayList<FTPFile> list = new ArrayList<FTPFile>(Arrays.asList(ftpFiles));
  240. Collections.sort(list, new Comparator<FTPFile>() {
  241. @Override
  242. public int compare(FTPFile o1, FTPFile o2) {
  243. long time = o1.getTimestamp().getTime().getTime();
  244. long time1 = o2.getTimestamp().getTime().getTime();
  245. if (time > time1) {
  246. return 1;
  247. }
  248. if (time == time1) {
  249. return 0;
  250. }
  251. return -1;
  252. }
  253. });
  254. for (FTPFile file : list) {
  255. if (file.getName().toUpperCase().endsWith("." + fileType)) {
  256. File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
  257. OutputStream os = new FileOutputStream(localFile);
  258. ftpClient.retrieveFile(file.getName(), os);
  259. os.close();
  260. files.add(localFile);
  261. }
  262. }
  263. }
  264. } catch (Exception e) {
  265. BaseUtil.getLogger().error(e.toString());
  266. e.printStackTrace();
  267. }
  268. return files;
  269. }
  270. /**
  271. *
  272. * @param ftpClient
  273. * @return 获取连接到的ftp站点下的文件夹所有文件
  274. */
  275. public static List<File> downloadFileByDirectory(FTPClient ftpClient,String directory) {
  276. List<File> files = new ArrayList<File>();
  277. try {
  278. ftpClient.enterLocalPassiveMode();
  279. // 转移到FTP服务器目录
  280. ftpClient.changeWorkingDirectory("/" + directory);
  281. FTPFile[] ftpFiles = ftpClient.listFiles();
  282. if (ftpFiles != null && ftpFiles.length > 0) {
  283. ArrayList<FTPFile> list = new ArrayList<FTPFile>(Arrays.asList(ftpFiles));
  284. Collections.sort(list, new Comparator<FTPFile>() {
  285. @Override
  286. public int compare(FTPFile o1, FTPFile o2) {
  287. long time = o1.getTimestamp().getTime().getTime();
  288. long time1 = o2.getTimestamp().getTime().getTime();
  289. if (time > time1) {
  290. return 1;
  291. }
  292. if (time == time1) {
  293. return 0;
  294. }
  295. return -1;
  296. }
  297. });
  298. for (FTPFile file : list) {
  299. if(!".".equals(file.getName()) && !"..".equals(file.getName())&& !"bak".equals(file.getName())&& !"failed".equals(file.getName())) {
  300. File localFile = new File(System.getProperty("java.io.tmpdir") + File.separator + file.getName());
  301. OutputStream os = new FileOutputStream(localFile);
  302. ftpClient.retrieveFile(file.getName(), os);
  303. os.close();
  304. files.add(localFile);
  305. }
  306. }
  307. }
  308. } catch (Exception e) {
  309. BaseUtil.getLogger().error(e.toString());
  310. e.printStackTrace();
  311. }
  312. return files;
  313. }
  314. }