当前位置:   article > 正文

ftp代码编写时遇到的坑_ftpreply.ispositivecompletion

ftpreply.ispositivecompletion

目录

1.上传服务器上的文件中文名乱码

2.读取ftp路径下的文件

3.配置ftp下载时的编码转换

4.ftp的maven依赖

5.ftp工具类


1.上传服务器上的文件中文名乱码

解决:需要设置linux服务器的编码问题 

首先判断服务器是否支持中文,使用echo $LANG 命令测试

如果不是中文,需要修改如下:(临时)

1、locale

2.临时更换系统语言

LANG="zh_CN.UTF-8"

3.修改系统默认语言

2.读取ftp路径下的文件

首先需要下载到指定的目录中,然后才能解析读取

3.配置ftp下载时的编码转换

4.ftp的maven依赖

  1. <dependency>
  2. <groupId>commons-net</groupId>
  3. <artifactId>commons-net</artifactId>
  4. <version>1.4.1</version>
  5. </dependency>

5.ftp工具类

详细代码:看github

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.apache.commons.net.ftp.FTPClient;
  3. import org.apache.commons.net.ftp.FTPFile;
  4. import org.apache.commons.net.ftp.FTPReply;
  5. import org.apache.poi.hssf.usermodel.HSSFSheet;
  6. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  7. import org.springframework.stereotype.Component;
  8. import java.io.*;
  9. import java.net.SocketException;
  10. import java.text.SimpleDateFormat;
  11. import java.util.*;
  12. @Component
  13. @Slf4j
  14. public class FTPUtil {
  15. /**
  16. * 打开FTP服务链接
  17. * @param ftpHost
  18. * @param ftpPort
  19. * @param ftpUserName
  20. * @param ftpPassword
  21. */
  22. public static FTPClient getFTPClient(String ftpHost, Integer ftpPort, String ftpUserName, String ftpPassword){
  23. FTPClient ftpClient = null;
  24. try {
  25. ftpClient = new FTPClient();
  26. ftpClient.setConnectTimeout(60000);
  27. if(ftpPort != null){
  28. ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
  29. }else {
  30. ftpClient.connect(ftpHost);// 连接FTP服务器
  31. }
  32. if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
  33. if (ftpClient.login(ftpUserName, ftpPassword)) {// 登陆FTP服务器
  34. if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
  35. "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
  36. ftpClient.setControlEncoding("UTF-8");
  37. }else {
  38. ftpClient.setControlEncoding("GBK");
  39. }
  40. ftpClient.enterLocalPassiveMode();// 设置被动模式
  41. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置传输的模式,以二进制流的方式读取
  42. ftpClient.enterLocalPassiveMode();
  43. System.out.println("FTP服务连接成功!");
  44. }else {
  45. System.out.println("FTP服务用户名或密码错误!");
  46. disConnection(ftpClient);
  47. }
  48. }else {
  49. System.out.println("连接到FTP服务失败!");
  50. disConnection(ftpClient);
  51. }
  52. } catch (SocketException e) {
  53. e.printStackTrace();
  54. disConnection(ftpClient);
  55. System.out.println("FTP的IP地址可能错误,请正确配置。");
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. disConnection(ftpClient);
  59. System.out.println("FTP的端口错误,请正确配置。");
  60. }
  61. return ftpClient;
  62. }
  63. /**
  64. * 关闭FTP服务链接
  65. * @throws IOException
  66. */
  67. public static void disConnection(FTPClient ftpClient){
  68. try {
  69. if(ftpClient.isConnected()){
  70. ftpClient.disconnect();
  71. }
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. }
  75. }
  76. /**
  77. * 获取文件夹下的所有文件信息
  78. * @param path 文件路径
  79. */
  80. public static FTPFile[] getFTPDirectoryFiles(FTPClient ftpClient,String path){
  81. FTPFile[] files = null;
  82. try {
  83. ftpClient.changeWorkingDirectory(path);
  84. files = ftpClient.listFiles();
  85. log.info(files.toString());
  86. }catch (Exception e){
  87. e.printStackTrace();
  88. //关闭连接
  89. disConnection(ftpClient);
  90. System.out.println("FTP读取数据异常!");
  91. }
  92. return files;
  93. }
  94. /**
  95. * 获取文件夹下的所有文件信息
  96. * @param path 文件路径
  97. */
  98. public static InputStream getFTPFile(FTPClient ftpClient,String path,String fileName){
  99. InputStream in = null;
  100. try {
  101. ftpClient.changeWorkingDirectory(path);
  102. FTPFile[] files = ftpClient.listFiles();
  103. if(files.length > 0){
  104. in = ftpClient.retrieveFileStream(fileName);
  105. }
  106. }catch (Exception e){
  107. e.printStackTrace();
  108. System.out.println("FTP读取数据异常!");
  109. }finally {
  110. //关闭连接
  111. disConnection(ftpClient);
  112. }
  113. return in;
  114. }
  115. /**
  116. * 下载ftp服务器文件方法
  117. * @param ftpClient FTPClient对象
  118. * @param newFileName 新文件名
  119. * @param fileName 原文件(路径+文件名)
  120. * @param downUrl 下载路径
  121. * @return
  122. * @throws IOException
  123. */
  124. public static boolean downFile(FTPClient ftpClient, String newFileName, String fileName, String downUrl) throws IOException {
  125. boolean isTrue = false;
  126. OutputStream os=null;
  127. File localFile = new File(downUrl + "/" + newFileName);
  128. if (!localFile.getParentFile().exists()){//文件夹目录不存在创建目录
  129. localFile.getParentFile().mkdirs();
  130. localFile.createNewFile();
  131. }
  132. os = new FileOutputStream(localFile);
  133. isTrue =ftpClient.retrieveFile(new String(fileName.getBytes("utf-8"),"iso-8859-1"), os);
  134. os.close();
  135. return isTrue;
  136. }
  137. public static void main(String args[]){
  138. InputStream in = null;
  139. BufferedReader br = null;
  140. FTPClient ftpClient1 = null;
  141. try{
  142. String path = "/var/ftp/aaa/";//设置ftp文件所在的目录
  143. //读取单个文件
  144. /*FTPClient ftpClient = getFTPClient("159.226.16.187",21,"zxd","1a2b3c");
  145. String fileName = "person.txt";
  146. in = getFTPFile(ftpClient,path,fileName);
  147. if(in != null){
  148. br = new BufferedReader(new InputStreamReader(in,"GBK"));
  149. String data = null;
  150. while ((data = br.readLine()) != null) {
  151. String[] empData = data.split(";");
  152. System.out.println(empData[0]+" "+empData[1]);
  153. }
  154. }*/
  155. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMmDDHHmmss");
  156. String dateStr = sdf.format(new Date());
  157. //读取文件夹下的所有文件
  158. ftpClient1 = getFTPClient("159.226.16.187",21,"zxd","1a2b3c");
  159. FTPFile[] files = getFTPDirectoryFiles(ftpClient1,path);
  160. //List<String> list = new ArrayList<String>();
  161. if(files != null && files.length > 0){
  162. for (int i = 0; i < files.length; i++) {
  163. if(files[i].isFile()){
  164. //in = ftpClient1.retrieveFileStream(remotePath);
  165. // br = new BufferedReader(new InputStreamReader(in,"GBK"));
  166. //只读取文件后缀名为.docx的文件
  167. if(files[i].getName().indexOf(".docx")>=0 &&files[i].getName().length() == (files[i].getName().lastIndexOf(".docx") + ".docx".length())){
  168. /*System.out.println("获取的文件名:>>>>>>>>>>>>>>>>>>>>"+files[i].getName());
  169. String NewfileName="ddd"+dateStr+".docx";
  170. boolean flag =downFile(ftpClient1,NewfileName,path+files[i].getName(),"D:\\file\\");
  171. System.out.println(flag);//flag=true说明下载成功
  172. WebLoophole bean = new WebLoophole();*/
  173. try {
  174. /*String remotePath="D:\\file\\"+NewfileName;
  175. log.info("文件路径输出>>>>>>>>>>>>>>>>>>>>>>>>>>=========>"+remotePath);
  176. List<String> list = POIUtil.readWord("D:\\file\\");
  177. if( list !=null){
  178. bean.setWebName(list.get(5));
  179. DateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
  180. String replace = list.get(13).replace("年", "-").replace("月", "-").replace("日", "-");
  181. bean.setScanTime(sdf1.parse(replace));
  182. bean.setLoopholeTotal(Integer.parseInt(list.get(35).split(" ")[1]));
  183. bean.setDomain(list.get(22).split("\t")[1]);
  184. bean.setWebUrl(list.get(21).split("\t")[1]);
  185. String [] numArray = list.get(33).split("\t");
  186. bean.setCritical(Integer.parseInt(numArray[0]));
  187. bean.setHigh(Integer.parseInt(numArray[1]));
  188. bean.setMiddle(Integer.parseInt(numArray[2]));
  189. bean.setLow(Integer.parseInt(numArray[3]));
  190. log.info("数据输出=========>"+bean);
  191. //searchDataMapper.insertWebLoopholeLog(bean);
  192. }*/
  193. } catch (Exception e) {
  194. log.error("{}",e);
  195. }finally {
  196. /*Process process =null;
  197. //读取完文件内容,执行脚本命令清空
  198. String command1 ="rm "+" "+filePath;
  199. try {
  200. Runtime.getRuntime().exec(command1 ).waitFor();
  201. } catch (IOException e1) {
  202. log.error("{}",e1);
  203. }catch (InterruptedException e) {
  204. log.error("{}",e);
  205. }*/
  206. }
  207. }else{
  208. System.out.println("获取的文件名:>>>>>>>>>>>>>>>>>>>>"+files[i].getName());
  209. String filePath="D:\\file1\\";
  210. boolean flag =downFile(ftpClient1,files[i].getName(),path+files[i].getName(),filePath);
  211. System.out.println(flag);//flag=true说明下载成功*/
  212. File[] dirFiles = new File(filePath).listFiles();
  213. String fileName = null;
  214. List<Map<String,Object>> list = null;
  215. InputStream is = null;
  216. for(File temp : dirFiles){
  217. //获取文件路径,包含文件名
  218. filePath = temp.getAbsolutePath();
  219. //获取文件名
  220. fileName = temp.getName();
  221. System.out.println(temp.isFile() + " " + temp.getAbsolutePath());
  222. // 创建输入流,读取Excel
  223. try {
  224. File file1 = new File(filePath);
  225. System.out.println(file1.getAbsolutePath());
  226. is = new FileInputStream(file1.getAbsolutePath());
  227. list = new ArrayList<Map<String,Object>>();
  228. // jxl提供的Workbook类
  229. HSSFWorkbook workbook = new HSSFWorkbook(is);
  230. Map<String,Object> map = null;
  231. for (int n = 0; n < workbook.getNumberOfSheets(); n++) {
  232. if(workbook.getNumberOfSheets() == 0){
  233. System.out.println("输出为空>>>>>>>>>>>>>>>");
  234. //return list;
  235. }
  236. HSSFSheet sheet = workbook.getSheetAt(i);
  237. System.out.println(sheet.getLastRowNum());
  238. for (int j = 1; j <= sheet.getLastRowNum(); j++) {
  239. if(j == 1){
  240. continue;
  241. }
  242. map = new HashMap<String,Object>();
  243. String ip = sheet.getRow(j).getCell(0)==null?"":sheet.getRow(j).getCell(0).toString().trim();
  244. String machinName = sheet.getRow(j).getCell(1)==null?"":sheet.getRow(j).getCell(1).toString().trim();
  245. String name = sheet.getRow(j).getCell(2)==null?"":sheet.getRow(j).getCell(2).toString().trim();
  246. String riskLevel = sheet.getRow(j).getCell(3)==null?"":sheet.getRow(j).getCell(3).toString().trim();
  247. String stagery = sheet.getRow(j).getCell(4)==null?"":sheet.getRow(j).getCell(4).toString().trim();
  248. String status = sheet.getRow(j).getCell(5)==null?"":sheet.getRow(j).getCell(5).toString().trim();
  249. String descript = sheet.getRow(j).getCell(6)==null?"":sheet.getRow(j).getCell(6).toString().trim();
  250. Date createTime = sheet.getRow(j).getCell(7).getDateCellValue();
  251. map.put("ip", ip);
  252. map.put("machinName", machinName);
  253. map.put("name", name);
  254. map.put("riskLevel", riskLevel);
  255. map.put("stagery", stagery);
  256. map.put("status", status);
  257. map.put("descript", descript);
  258. //Date date = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss").parse(createTime);
  259. map.put("createTime", createTime);
  260. list.add(map);
  261. //searchDataMapper.insertHostLog(list);
  262. }
  263. }
  264. } catch (Exception e) {
  265. e.printStackTrace();
  266. }
  267. }
  268. // return list;
  269. }
  270. }
  271. }
  272. }
  273. }catch (Exception e){
  274. e.printStackTrace();
  275. }finally {
  276. try{
  277. //关闭连接
  278. disConnection(ftpClient1);
  279. //关闭流
  280. if (br != null)
  281. br.close();
  282. if (in != null)
  283. in.close();
  284. }catch (IOException e){
  285. e.printStackTrace();
  286. }
  287. }
  288. }
  289. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/255504?site
推荐阅读
相关标签
  

闽ICP备14008679号