ftpClient 的上传下载及删除

考虑到以后可能用到这些代码,还是决定分享出来,方便以后查找参考。 


1、上传文件

        /**
	 * 上传文件到ftp.
	 * 
	 * @param inputStream
	 * @param pathString
	 * @param filename
	 * @return
	 */
	public boolean uploadFile(ByteArrayInputStream inputStream, String pathString, String fileName) throws Exception {

		boolean flag = false;
		if (!initConnect()) {
			return false;
		}
		try {
			if (!existDirectory(pathString)) {
				flag = createDirectory(pathString);
			}
			// 变更工作路径
			flag = ftpClient.changeWorkingDirectory("/" + pathString);
			// 存储文件
			flag = ftpClient.storeFile(new String(fileName.getBytes("GBK"), "iso-8859-1"), inputStream);
		} catch (IOException e) {
			e.printStackTrace();
			// 失败后删除上传的文件
			removeDirectory(pathString, new String(fileName.getBytes("GBK"), "iso-8859-1"));
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e2) {
				}
			}
		}
		return flag;
	}

2、下载文件


    /**
     * 从Ftp上下载一个文件
     * 
     * @param fileName
     * @return InputStream
     * @throws IOException 
     */
    public InputStream downloadFile(String remotePath, String fileName)  {
        InputStream is =null;
        FTPFile[] fs;
        try{
            this.initConnect();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);    <pre name="code" class="java">            // 转移到FTP服务器目录
            ftpClient.changeWorkingDirectory("/"+remotePath);
            //fs = ftpClient.listFiles();
             //检查远程文件是否存在   
            fs = ftpClient.listFiles(new String(fileName.getBytes("GBK"),"iso-8859-1"));
            if(fs.length == 1){   
                is = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"),"iso-8859-1"));   
                return is;
            }  
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return is;
    }

 

3、删除文件

     <pre name="code" class="html">            public boolean removeDirectory(String path, String fileName) throws IOException{
			this.initConnect();
			try {
				// 获取当前Ftp服务器登录目录,主要是解决Linux下Ftp服务器删除附件问题
				String curDirectory = ftpClient.printWorkingDirectory();
				if (JqLib.isEmpty(curDirectory)) {// 若为空,则定位到根目录
					curDirectory = "";
				}
				// 删除文件
				boolean flag = ftpClient.changeWorkingDirectory(curDirectory + "/" + rootpath + "/" + path);// 转移到FTP服务器目录
				flag = ftpClient.deleteFile(new String(fileName.getBytes("GBK"), "iso-8859-1"));
				if (!flag) {
					throw new UploadNotSuccessException("FTP附件删除失败!");
				}

				// 删除文件夹
				flag = ftpClient.changeWorkingDirectory("/" + rootpath);

				return ftpClient.removeDirectory(path);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				this.closeConnect();
			}
			return true;
		}

 

4、删除并备份文件(这里的删除实际是备份文件,将历史文件保存了下来,放在另外一个文件夹里面)

      public boolean removeDirectory(String path, String fileName) throws IOException{
		this.initConnect();
		try {
			boolean flag = false;
			String ftpFileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
			// 获取当前Ftp服务器登录目录,主要是解决Linux下Ftp服务器删除附件问题
			String curDirectory = ftpClient.printWorkingDirectory();
			if (JqLib.isEmpty(curDirectory)) {// 若为空,则定位到根目录
				curDirectory = "";
			}

			// 获得时间戳
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String datePrint = sdf.format(new Date());

			// 拼接目录
			String pathString = curDirectory + "/" + rootpath + "/" + path;
			String pathStringTrash = curDirectory + "/" + rootpath_trash + "/" + path + "_" + datePrint;

			if (!existDirectory(pathStringTrash) && testPath(pathString)) {
				flag = ftpClient.makeDirectory(pathStringTrash);
			}
			// 源文件存在时才移动
			if (testPath(pathString)) {
				// 移动文件
				flag = ftpClient.rename(pathString + "/" + ftpFileName, pathStringTrash + "/" + ftpFileName);
				
				if (!flag) {
					System.out.println("FTP附件移动失败");
				}
				// 删除文件夹
				flag = ftpClient.changeWorkingDirectory("/" + rootpath);
			}else{
				System.out.println("源文件路径 " + path + "不存在");
			}
			return ftpClient.removeDirectory(path);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			this.closeConnect();
		}
		return true;
	}

5、其他相关方法

  <pre name="code" class="java">       /**
	 * 连接参数初始化
	 */
	public boolean initConnect() {
		try {
			if (ftpClient == null) { // 如果为空,则初始化连接
				if (!isConnectFtp()) {
					return false;
				}
			} else { // 如果不为空,则定位到根目录
				ftpClient.cwd("/"+rootpath);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 检查文件夹在当前目录下是否存在
	 * 
	 * @param path 目录路径
	 * @return
	 * @throws IOException boolean
	 */
	public boolean existDirectory(String path) throws IOException {
		boolean flag = false;
		FTPFile[] ftpFileArr = ftpClient.listFiles(path);
		for (FTPFile ftpFile : ftpFileArr) {
			if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(path)) {
				flag = true;
				break;
			}
		}
		return flag;
	}  
    
    /**
     * 创建文件目录
     * 
     * @param pathName 目录路径
     * @return
     * @throws IOException boolean
     */
	public boolean createDirectory(String pathName) throws IOException {
		String[] path = pathName.split("/");
		FTPFile[] file = null;
		for(int j=0;j<path.length;j++) {
			try {
				file = ftpClient.listFiles(path[j]);
				if(file.length==0) {
					throw new Exception();
				}
			}catch(Exception e) {
				//不存在此目录
				ftpClient.makeDirectory(path[j]);
			}finally {
				ftpClient.changeWorkingDirectory(path[j]);
			}
		}
		return true;
	}

   /**
     * 测试Ftp服务器是否联通
     * 
     * @return boolean
     */
    public boolean isConnectFtp() {
        boolean isConnect = true;
        ftpClient = new FTPClient();
        int reply;
        try {
            if (this.port != -1) {
                ftpClient.setDefaultPort(port);
            } else { 
                ftpClient.connect(ip);
            }
            ftpClient.connect(ip);
            ftpClient.login(this.username, this.password);
            reply = ftpClient.getReplyCode();
            ftpClient.setDataTimeout(120000);
               //设置PassiveMode传输   
            ftpClient.enterLocalPassiveMode();   
            //设置以二进制流的方式传输   
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);   
            ftpClient.setControlEncoding("UTF-8");   
            
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                isConnect = false;
            }

            return isConnect;
        } catch (SocketException e) {
            isConnect = false;
            e.printStackTrace();
        } catch (IOException e) {
            isConnect = false;
            
        }
        return isConnect;
    }
 



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值