JAVA中使用FTPClient实现文件上传下载(键人岐)

 在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。
  1. 所用到的jar包有:  
  2. commons-net-1.4.1.jar  
  3. jakarta-oro.jar  
一、上传文件
01 文件上传源代码 
02             /**  
03      * Description: 向FTP服务器上传文件  
04      * @Version1.0  
05      * @param url FTP服务器hostname  
06      * @param port FTP服务器端口  
07      * @param username FTP登录账号  
08      * @param password FTP登录密码  
09      * @param path FTP服务器保存目录  
10      * @param filename 上传到FTP服务器上的文件名  
11      * @param input 输入流  
12      * @return 成功返回true,否则返回false  
13      */   
14     public static boolean uploadFile( 
15             String url,//FTP服务器hostname  
16             int port,//FTP服务器端口 
17             String username, // FTP登录账号  
18             String password, //FTP登录密码 
19             String path, //FTP服务器保存目录 
20             String filename, //上传到FTP服务器上的文件名  
21             InputStream input // 输入流  
22             ) {   
23         boolean success = false;   
24         FTPClient ftp = new FTPClient();   
25         try {   
26             int reply;   
27             ftp.connect(url, port);//连接FTP服务器    
28             //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器    
29             ftp.login(username, password);//登录    
30             reply = ftp.getReplyCode();   
31             if (!FTPReply.isPositiveCompletion(reply)) {   
32                 ftp.disconnect();   
33                 return success;   
34             }   
35             ftp.changeWorkingDirectory(path);   
36             ftp.storeFile(filename, input);            
37                  
38             input.close();   
39             ftp.logout();   
40             success = true;   
41         catch (IOException e) {   
42             e.printStackTrace();   
43         finally {   
44             if (ftp.isConnected()) {   
45                 try {   
46                     ftp.disconnect();   
47                 catch (IOException ioe) {   
48                 }   
49             }   
50         }   
51         return success;   
52     }
以下是文件上传的测试用例:
01 /** 
02  * 将本地文件上传到FTP服务器上 
03  
04  */ 
05 public void testUpLoadFromDisk(){   
06     try {   
07         FileInputStream in=new FileInputStream(new File("D:/test.txt"));   
08         boolean flag = uploadFile("127.0.0.1"21"administrator""zyuc2011""test","test.txt", in);   
09         System.out.println(flag);   
10     catch (FileNotFoundException e) {   
11         e.printStackTrace();   
12     }    
13 }
01 /** 
02  * 在FTP服务器上生成一个文件,并将一个字符串写入到该文件中 
03  
04  */ 
05 public void testUpLoadFromString(){   
06     try {   
07         String str = "这是要写入的字符串!"
08         InputStream input = new ByteArrayInputStream(str.getBytes("utf-8"));   
09         boolean flag = uploadFile("127.0.0.1"21"administrator""zyuc2011""test","test.txt", input);   
10         System.out.println(flag);   
11     catch (UnsupportedEncodingException e) {   
12         e.printStackTrace();   
13     }   
14 }
二、文件下载
01 文件下载源代码 
02     /**  
03      * Description: 从FTP服务器下载文件  
04      * @Version1.0  
05      * @param url FTP服务器hostname  
06      * @param port FTP服务器端口  
07      * @param username FTP登录账号  
08      * @param password FTP登录密码  
09      * @param remotePath FTP服务器上的相对路径  
10      * @param fileName 要下载的文件名  
11      * @param localPath 下载后保存到本地的路径  
12      * @return  
13      */   
14     public static boolean downFile( 
15             String url, //FTP服务器hostname 
16             int port,//FTP服务器端口 
17             String username, //FTP登录账号 
18             String password, //FTP登录密码 
19             String remotePath,//FTP服务器上的相对路径  
20             String fileName,//要下载的文件名 
21             String localPath//下载后保存到本地的路径 
22             ) {   
23         boolean success = false;   
24         FTPClient ftp = new FTPClient();   
25         try {   
26             int reply;   
27             ftp.connect(url, port);   
28             //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器    
29             ftp.login(username, password);//登录    
30             reply = ftp.getReplyCode();   
31             if (!FTPReply.isPositiveCompletion(reply)) {   
32                 ftp.disconnect();   
33                 return success;   
34             }   
35             ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录    
36             FTPFile[] fs = ftp.listFiles();   
37             for(FTPFile ff:fs){   
38                 if(ff.getName().equals(fileName)){   
39                     File localFile = new File(localPath+"/"+ff.getName());   
40                     OutputStream is = new FileOutputStream(localFile);    
41                     ftp.retrieveFile(ff.getName(), is);   
42                     is.close();   
43                 }   
44             }   
45                  
46             ftp.logout();   
47             success = true;   
48         catch (IOException e) {   
49             e.printStackTrace();   
50         finally {   
51             if (ftp.isConnected()) {   
52                 try {   
53                     ftp.disconnect();   
54                 catch (IOException ioe) {   
55                 }   
56             }   
57         }   
58         return success;   
59     }
以下是文件下载的测试用例:
01 /** 
02  * 将FTP服务器上文件下载到本地 
03  
04  */ 
05 public void testDownFile(){ 
06     try {   
07         boolean flag = downFile("127.0.0.1"21"administrator""zyuc2011""test","test.txt""D:/");   
08         System.out.println(flag);   
09     catch (Exception e) {   
10         e.printStackTrace();   
11     }        
12 }
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹下文件及其子文件方法,添加了对文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除的文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件则删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除子文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件夹删除成功"); }else{ System.out.println(FtpFolder+"文件夹删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值