JAVA使用FTPClient类读写FTP

http://blog.csdn.net/kardelpeng/article/details/6588284

1.首先先导入相关jar包

2.创建一个连接FTP的工具类FTPUtil.java

[java]  view plain  copy
  1. package com.metarnet.ftp.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.SocketException;  
  6. import java.util.Properties;  
  7.   
  8. import org.apache.commons.net.ftp.FTPClient;  
  9. import org.apache.commons.net.ftp.FTPReply;  
  10. import org.apache.log4j.Logger;  
  11.   
  12. public class FTPUtil {  
  13.     private static Logger logger = Logger.getLogger(FTPUtil.class);  
  14.   
  15.       
  16.       
  17.     /** 
  18.      * 获取FTPClient对象 
  19.      * @param ftpHost FTP主机服务器 
  20.      * @param ftpPassword FTP 登录密码 
  21.      * @param ftpUserName FTP登录用户名 
  22.      * @param ftpPort FTP端口 默认为21 
  23.      * @return 
  24.      */  
  25.     public static FTPClient getFTPClient(String ftpHost, String ftpPassword,  
  26.             String ftpUserName, int ftpPort) {  
  27.         FTPClient ftpClient = null;  
  28.         try {  
  29.             ftpClient = new FTPClient();  
  30.             ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器  
  31.             ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器  
  32.             if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
  33.                 logger.info("未连接到FTP,用户名或密码错误。");  
  34.                 ftpClient.disconnect();  
  35.             } else {  
  36.                 logger.info("FTP连接成功。");  
  37.             }  
  38.         } catch (SocketException e) {  
  39.             e.printStackTrace();  
  40.             logger.info("FTP的IP地址可能错误,请正确配置。");  
  41.         } catch (IOException e) {  
  42.             e.printStackTrace();  
  43.             logger.info("FTP的端口错误,请正确配置。");  
  44.         }  
  45.         return ftpClient;  
  46.     }  
  47. }  

3.编写一个读取FTP上文件的类ReadFTPFile.java
[java]  view plain  copy
  1. package com.metarnet.ftp.read;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.net.SocketException;  
  10.   
  11. import org.apache.commons.net.ftp.FTPClient;  
  12. import org.apache.log4j.Logger;  
  13.   
  14. import com.metarnet.ftp.util.FTPUtil;  
  15.   
  16. public class ReadFTPFile {  
  17.     private Logger logger = Logger.getLogger(ReadFTPFile.class);  
  18.   
  19.     /** 
  20.      * 去 服务器的FTP路径下上读取文件 
  21.      *  
  22.      * @param ftpUserName 
  23.      * @param ftpPassword 
  24.      * @param ftpPath 
  25.      * @param FTPServer 
  26.      * @return 
  27.      */  
  28.     public String readConfigFileForFTP(String ftpUserName, String ftpPassword,  
  29.             String ftpPath, String ftpHost, int ftpPort, String fileName) {  
  30.         StringBuffer resultBuffer = new StringBuffer();  
  31.         FileInputStream inFile = null;  
  32.         InputStream in = null;  
  33.         FTPClient ftpClient = null;  
  34.         logger.info("开始读取绝对路径" + ftpPath + "文件!");  
  35.         try {  
  36.             ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPassword, ftpUserName,  
  37.                     ftpPort);  
  38.             ftpClient.setControlEncoding("UTF-8"); // 中文支持  
  39.             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
  40.             ftpClient.enterLocalPassiveMode();  
  41.             ftpClient.changeWorkingDirectory(ftpPath);  
  42.             in = ftpClient.retrieveFileStream(fileName);  
  43.         } catch (FileNotFoundException e) {  
  44.             logger.error("没有找到" + ftpPath + "文件");  
  45.             e.printStackTrace();  
  46.             return "下载配置文件失败,请联系管理员.";  
  47.         } catch (SocketException e) {  
  48.             logger.error("连接FTP失败.");  
  49.             e.printStackTrace();  
  50.         } catch (IOException e) {  
  51.             e.printStackTrace();  
  52.             logger.error("文件读取错误。");  
  53.             e.printStackTrace();  
  54.             return "配置文件读取失败,请联系管理员.";  
  55.         }  
  56.         if (in != null) {  
  57.             BufferedReader br = new BufferedReader(new InputStreamReader(in));  
  58.             String data = null;  
  59.             try {  
  60.                 while ((data = br.readLine()) != null) {  
  61.                     resultBuffer.append(data + "\n");  
  62.                 }  
  63.             } catch (IOException e) {  
  64.                 logger.error("文件读取错误。");  
  65.                 e.printStackTrace();  
  66.                 return "配置文件读取失败,请联系管理员.";  
  67.             }finally{  
  68.                 try {  
  69.                     ftpClient.disconnect();  
  70.                 } catch (IOException e) {  
  71.                     e.printStackTrace();  
  72.                 }  
  73.             }  
  74.         }else{  
  75.             logger.error("in为空,不能读取。");  
  76.             return "配置文件读取失败,请联系管理员.";  
  77.         }  
  78.         return resultBuffer.toString();  
  79.     }  
  80. }  
4.创建一个往FTP上写入文件的类WriteFTPFile.java

[java]  view plain  copy
  1. package com.metarnet.ftp.write;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileWriter;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9.   
  10. import org.apache.commons.net.ftp.FTPClient;  
  11. import org.apache.commons.net.ftp.FTPFile;  
  12. import org.apache.log4j.Logger;  
  13.   
  14. import com.metarnet.ftp.util.FTPUtil;  
  15.   
  16. public class WriteFTPFile {  
  17.   
  18.     private Logger logger = Logger.getLogger(WriteFTPFile.class);  
  19.   
  20.     /** 
  21.      * 本地上传文件到FTP服务器 
  22.      *  
  23.      * @param ftpPath 
  24.      *            远程文件路径FTP 
  25.      * @throws IOException 
  26.      */  
  27.     public void upload(String ftpPath, String ftpUserName, String ftpPassword,  
  28.             String ftpHost, int ftpPort, String fileContent,  
  29.             String writeTempFielPath) {  
  30.         FTPClient ftpClient = null;  
  31.         logger.info("开始上传文件到FTP.");  
  32.         try {  
  33.             ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPassword,  
  34.                     ftpUserName, ftpPort);  
  35.             // 设置PassiveMode传输  
  36.             ftpClient.enterLocalPassiveMode();  
  37.             // 设置以二进制流的方式传输  
  38.             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
  39.             // 对远程目录的处理  
  40.             String remoteFileName = ftpPath;  
  41.             if (ftpPath.contains("/")) {  
  42.                 remoteFileName = ftpPath  
  43.                         .substring(ftpPath.lastIndexOf("/") + 1);  
  44.             }  
  45.             // FTPFile[] files = ftpClient.listFiles(new  
  46.             // String(remoteFileName));  
  47.             // 先把文件写在本地。在上传到FTP上最后在删除  
  48.             boolean writeResult = write(remoteFileName, fileContent,  
  49.                     writeTempFielPath);  
  50.             if (writeResult) {  
  51.                 File f = new File(writeTempFielPath + "/" + remoteFileName);  
  52.                 InputStream in = new FileInputStream(f);  
  53.                 ftpClient.storeFile(remoteFileName, in);  
  54.                 in.close();  
  55.                 logger.info("上传文件" + remoteFileName + "到FTP成功!");  
  56.                 f.delete();  
  57.             } else {  
  58.                 logger.info("写文件失败!");  
  59.             }  
  60.         } catch (Exception e) {  
  61.             e.printStackTrace();  
  62.         }finally{  
  63.             try {  
  64.                 ftpClient.disconnect();  
  65.             } catch (IOException e) {  
  66.                 e.printStackTrace();  
  67.             }  
  68.         }  
  69.     }  
  70.   
  71.     /** 
  72.      * 把配置文件先写到本地的一个文件中取 
  73.      *  
  74.      * @param ftpPath 
  75.      * @param str 
  76.      * @return 
  77.      */  
  78.     public boolean write(String fileName, String fileContext,  
  79.             String writeTempFielPath) {  
  80.         try {  
  81.             logger.info("开始写配置文件");  
  82.             File f = new File(writeTempFielPath + "/" + fileName);  
  83.             if(!f.exists()){  
  84.                 if(!f.createNewFile()){  
  85.                     logger.info("文件不存在,创建失败!");  
  86.                 }  
  87.             }  
  88.             BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));  
  89.             bw.write(fileContext.replaceAll("\n""\r\n"));  
  90.             bw.flush();  
  91.             bw.close();  
  92.             return true;  
  93.         } catch (Exception e) {  
  94.             logger.error("写文件没有成功");  
  95.             e.printStackTrace();  
  96.             return false;  
  97.         }  
  98.     }  
  99. }  

5.建立一个测试类FTPMain.java
[java]  view plain  copy
  1. package com.metarnet.ftp.main;  
  2.   
  3. import java.io.InputStream;  
  4. import java.util.Properties;  
  5.   
  6. import org.apache.log4j.Logger;  
  7.   
  8. import com.metarnet.ftp.read.ReadFTPFile;  
  9. import com.metarnet.ftp.util.FTPUtil;  
  10. import com.metarnet.ftp.write.WriteFTPFile;  
  11.   
  12. public class FTPMain {  
  13.       
  14.     private static Logger logger = Logger.getLogger(FTPMain.class);  
  15.   
  16.     public static void main(String[] args) {  
  17.         int ftpPort = 0;  
  18.         String ftpUserName = "";  
  19.         String ftpPassword = "";  
  20.         String ftpHost = "";  
  21.         String ftpPath = "";  
  22.         String writeTempFielPath = "";  
  23.         try {  
  24.             InputStream in = FTPUtil.class.getClassLoader()  
  25.                     .getResourceAsStream("env.properties");  
  26.             if (in == null) {  
  27.                 logger.info("配置文件env.properties读取失败");  
  28.             } else {  
  29.                 Properties properties = new Properties();  
  30.                 properties.load(in);  
  31.                 ftpUserName = properties.getProperty("ftpUserName");  
  32.                 ftpPassword = properties.getProperty("ftpPassword");  
  33.                 ftpHost = properties.getProperty("ftpHost");  
  34.                 ftpPort = Integer.valueOf(properties.getProperty("ftpPort"))  
  35.                         .intValue();  
  36.                 ftpPath = properties.getProperty("ftpPath");  
  37.                 writeTempFielPath = properties.getProperty("writeTempFielPath");  
  38.                   
  39.                 ReadFTPFile read = new ReadFTPFile();  
  40.                 String result = read.readConfigFileForFTP(ftpUserName, ftpPassword, ftpPath, ftpHost, ftpPort, "huawei_220.248.192.200.cfg");  
  41.                 System.out.println("读取配置文件结果为:" + result);  
  42.                   
  43.                 WriteFTPFile write = new WriteFTPFile();  
  44.                 ftpPath = ftpPath + "/" + "huawei_220.248.192.200_new1.cfg";  
  45.                 write.upload(ftpPath, ftpUserName, ftpPassword, ftpHost, ftpPort, result, writeTempFielPath);  
  46.             }  
  47.         } catch (Exception e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51. }  


最后肯定是执行,看最后执行结果。OK步骤已讲完。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值