`

ftp上传下载和zip压缩解压操作

阅读更多
package com.test.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;



public class FtpZipOption {
	
	/**
	 * 从ftp服务器下载zip文件
	 * @param 
	 *@throws Exception
	 **/
	public static void downLoadZipFile() throws Exception {

		

        String wantFileName = getWantFileName() ;//得到此时该下载的文件名
        String[] localFileNameArray = getLocalFileNameArray("D:\\download") ;//得到所有已经下载的文件名
        
        if(ifToDownLoadFile(wantFileName,localFileNameArray)){//判断是否需要下载
        	
        	String str; //输出信息字符串
    		/**   
    		 * 和服务器建立连接   
    		 */
    		FtpClient ftp = new FtpClient("192.168.39.189"); //根据服务器ip建立连接                          
    		str = ftp.getResponseString(); //获得响应信息
    		System.out.println("连接服务器:" + str);
    		/**   
    		 * 登陆到Ftp服务器   
    		 */
    		ftp.login("test", "test"); //根据用户名和密码登录服务器
    		str = ftp.getResponseString();
    		System.out.println("登录:"+str);
        	/**   
    		 * 打开并定位到服务器目录   
    		 */
    		ftp.cd("downziptest\\downzip"); //打开服务器上的文件目录
    		str = ftp.getResponseString() ;
    		System.out.println("打开服务器目录:"+str) ;
    		ftp.binary();//转化为二进制的文件
    		TelnetInputStream ftpIn = ftp.get(wantFileName+".zip");//找到要读取的文件
    		byte[] buf = new byte[204800];
    		int bufsize = 0;
    		String toLocalPath = "D:\\download\\"+wantFileName+".zip" ;
    		FileOutputStream ftpOut = new FileOutputStream(toLocalPath);
    		while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
    			ftpOut.write(buf, 0, bufsize);
    		}
    		ftpOut.close();
    		ftpIn.close();
    		System.out.println("下载"+wantFileName+".zip完成!") ;
        	
        }else{
        	System.out.println(wantFileName+".zip在本地已经存在,不予下载") ;
        }
		
	}
   //	上传文件;并返回上传文件的信息
	private static String upLoadZipToServer(String filename) throws Exception {
		String str; //输出信息字符串
		String timeStr = getNowTime();//获得当前时间
		String recordStr = "上传时间:" + timeStr + "\r\n";//信息记录字符串
		/**   
		 * 和服务器建立连接   
		 */
		FtpClient ftp = new FtpClient("192.168.39.189"); //根据服务器ip建立连接                          
		str = ftp.getResponseString(); //获得响应信息
		System.out.println(str);
		recordStr += "连接服务器:" + str + "\r\n";
		/**   
		 * 登陆到Ftp服务器   
		 */
		ftp.login("test", "test"); //根据用户名和密码登录服务器
		str = ftp.getResponseString();
		System.out.println(str);
		recordStr += "登录:" + str + "\r\n";
		/**   
		 * 打开并定位到test目录   
		 */
		ftp.cd("uptest"); //打开服务器上的test文件夹
		ftp.binary();//转化为二进制的文件
		str = ftp.getResponseString();
		System.out.println(str);
        
		FileInputStream is = null ;
		TelnetOutputStream os = null ;
	    try {
	      //"upftpfile"用ftp上传后的新文件名
	      os = ftp.put("uptest.zip");
	      File file_in = new java.io.File(filename);
	      if (file_in.length()==0) {
	         return "上传文件为空!";
	      }
	      is = new FileInputStream(file_in);
	      byte[] bytes = new byte[1024];
	      int c;
	      while ((c = is.read(bytes))!= -1) {
	         os.write(bytes, 0, c);
	      }
	  }finally {
	     if (is != null) {
	        is.close();
	     }
	    if (os != null) {
	      os.close();
	    }
	 }
	  return "上传文件成功!";
	}

	/**  
	 * zip压缩功能,压缩sourceFile(文件夹目录)下所有文件,包括子目录
	 * @param  sourceFile,待压缩目录; toFolerName,压缩完毕生成的目录
	 * @throws Exception  
	 */
	public static void fileToZip(String sourceFile, String toFolerName) throws Exception {

		List fileList = getSubFiles(new File(sourceFile)); //得到待压缩的文件夹的所有内容  
		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
				toFolerName));

		ZipEntry ze = null;
		byte[] buf = new byte[1024];
		int readLen = 0;
		for (int i = 0; i < fileList.size(); i++) { //遍历要压缩的所有子文件  
			File file = (File) fileList.get(i);
			System.out.println("压缩到的文件名:" + file.getName());
			ze = new ZipEntry(getAbsFileName(sourceFile, file));
			ze.setSize(file.length());
			ze.setTime(file.lastModified());
			zos.putNextEntry(ze);
			InputStream is = new BufferedInputStream(new FileInputStream(file));
			while ((readLen = is.read(buf, 0, 1024)) != -1) {
				zos.write(buf, 0, readLen);
			}
			is.close();
		}
		zos.close();
		System.out.println("压缩完成!");
	}

	/**
	 * 解压zip文件
	 * @param sourceFile,待解压的zip文件; toFolder,解压后的存放路径
	 * @throws Exception
	 **/
	public static void zipToFile(String sourceFile, String toFolder) throws Exception {

		String toDisk = toFolder;//接收解压后的存放路径
		ZipFile zfile = new ZipFile(sourceFile);//连接待解压文件
		System.out.println("要解压的文件是:" + zfile.getName());

		Enumeration zList = zfile.entries();//得到zip包里的所有元素
		ZipEntry ze = null;
		byte[] buf = new byte[1024];

		while (zList.hasMoreElements()) {
			ze = (ZipEntry) zList.nextElement();
			if (ze.isDirectory()) {
				System.out.println("打开zip文件里的文件夹:" + ze.getName()
						+ " skipped...");
				continue;
			}
			System.out.println("zip包里的文件: " + ze.getName() + "\t" + "大小为:"
					+ ze.getSize() + "KB");

			//以ZipEntry为参数得到一个InputStream,并写到OutputStream中
			OutputStream outputStream = new BufferedOutputStream(
					new FileOutputStream(getRealFileName(toDisk, ze.getName())));
			InputStream inputStream = new BufferedInputStream(zfile
					.getInputStream(ze));
			int readLen = 0;
			while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
				outputStream.write(buf, 0, readLen);
			}
			inputStream.close();
			outputStream.close();
			System.out.println("已经解压出:" + ze.getName());
		}
		zfile.close();
	}

	/**  
	 * 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.  
	 * @param baseDir java.lang.String 根目录  
	 * @param realFileName java.io.File 实际的文件名  
	 * @return 相对文件名  
	 */
	private static String getAbsFileName(String baseDir, File realFileName) {
		File real = realFileName;
		File base = new File(baseDir);
		String ret = real.getName();
		while (true) {
			real = real.getParentFile();
			if (real == null)
				break;
			if (real.equals(base))
				break;
			else
				ret = real.getName() + "/" + ret;
		}
		return ret;
	}

	/**  
	 * 取得指定目录下的所有文件列表,包括子目录.  
	 * @param baseDir File 指定的目录  
	 * @return 包含java.io.File的List  
	 */
	private static List<File> getSubFiles(File baseDir) {
		List<File> ret = new ArrayList<File>();
		File[] tmp = baseDir.listFiles();
		for (int i = 0; i < tmp.length; i++) {
			if (tmp[i].isFile())
				ret.add(tmp[i]);
			if (tmp[i].isDirectory())
				ret.addAll(getSubFiles(tmp[i]));
		}
		return ret;
	}

	/**
	 * 给定根目录,返回一个相对路径所对应的实际文件名.
	 * @param zippath 指定根目录
	 * @param absFileName 相对路径名,来自于ZipEntry中的name
	 * @return java.io.File 实际的文件
	 */
	private static File getRealFileName(String zippath, String absFileName){

		String[] dirs = absFileName.split("/", absFileName.length());
		File ret = new File(zippath);// 创建文件对象
		if (dirs.length > 1) {
			for (int i = 0; i < dirs.length - 1; i++) {
				ret = new File(ret, dirs[i]);
			}
		}
		if (!ret.exists()) {// 检测文件是否存在
			ret.mkdirs();// 创建此抽象路径名指定的目录
		}
		ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child 路径名字符串创建一个新 File 实例
		return ret;
	}
	/**
	 * 取得ftp服务器上某个目录下的所有文件名
	 * @param ftp, FtpClient类实例; folderName,服务器的文件夹名
	 * @throws Exception
	 * @return list 某目录下文件名列表
	 **/
	private static List getServerFileNameList(FtpClient ftp,String folderName) throws Exception{
                        
		BufferedReader dr = new BufferedReader(new InputStreamReader(ftp.nameList(folderName)));
		List<String> list = new ArrayList<String>() ;
		String s;
		while((s=dr.readLine())!=null){
			list.add(s) ;
		}
		return list ;
	}
	/**
	 * 得到已经下载的目录下的所有文件名的数组
	 * @param localPath 本地的下载文件保存路径
	 * @return 该路径下所有文件名
	 * **/
	private static String[] getLocalFileNameArray(String localPath){
		File diskFile = new File(localPath);
		if(diskFile!=null){
			String[] fileNameList = diskFile.list() ;
			return fileNameList ;
		}else{
			return null ;
		}
	}
	
	/**
	 *获得当前系统时间 
	 */
	public static String getNowTime() {
		String timeStr;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		Date currentTime = new Date(System.currentTimeMillis());
		timeStr = format.format(currentTime);
		return timeStr;
	}
	public static  String getWantFileName() throws Exception{
		/**得到当前的系统精确时间**/
		Date currentTime = new Date(System.currentTimeMillis());
        /**接下来得到系统当前的年月日**/
		DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
		Date todayDate = new Date(System.currentTimeMillis()) ;
		String todayStr =  df1.format(todayDate) ;//得到当前的年月日
		/**接下来得到四个比较时间的String类型;分别在00点,06点,12点和18点**/
		String  compareTimeStr1 = todayStr+"00";
		String  compareTimeStr2 = todayStr+"06";
		String  compareTimeStr3 = todayStr+"12";
		String  compareTimeStr4 = todayStr+"18";
		/**接下来得到四个比较时间的date类型**/
		DateFormat df2 = new SimpleDateFormat("yyyyMMddHH");
		Date compareTime1 = df2.parse(compareTimeStr1) ;
		Date compareTime2 = df2.parse(compareTimeStr2) ;
		Date compareTime3 = df2.parse(compareTimeStr3) ;
		Date compareTime4 = df2.parse(compareTimeStr4) ;
		/**接下来由当前系统时间和四个参照时间进行比较,找出该下载的文件名**/
		if(currentTime.after(compareTime1)&&currentTime.before(compareTime2)){
			//此时应该下载00点的文件,文件名为:compareTimeStr1
			System.out.println("此时要下载的文件名为:"+compareTimeStr1+".zip") ;
			return compareTimeStr1 ;
		}else if(currentTime.after(compareTime2)&&currentTime.before(compareTime3)){
			//此时应该下载06点的文件,文件名为:compareTimeStr2
			System.out.println("此时要下载的文件名为:"+compareTimeStr2+".zip") ;
			return compareTimeStr2;
		}else if(currentTime.after(compareTime3)&&currentTime.before(compareTime4)){
			//此时应该下载12点的文件,文件名为:compareTimeStr3
			System.out.println("此时要下载的文件名为:"+compareTimeStr3+".zip") ;
			return compareTimeStr3 ;
		}else if(currentTime.after(compareTime4)){
			//此时应该下载18点的文件,文件名为:compareTimeStr4
			System.out.println("此时要下载的文件名为:"+compareTimeStr4+".zip") ;
			return compareTimeStr4 ;
		}else{
			//nothing to do
			return null ;
		}
	}
	/**
	 * 判断此时是否需要下载文件
	 * @param wantFileName,此时该下载的文件名; localFileNameArray ,本地已经有的文件名
	 * @return ture--需要下载; false--本地已经有了,不需要下载
	 * **/
	public static boolean ifToDownLoadFile(String wantFileName,String[] localFileNameArray){
		
			if(wantFileName==null&&localFileNameArray==null){//当想要下载的文件名获得失败
				return false ;
			}else if(wantFileName==null&&localFileNameArray!=null){//当想要下载的文件名获得失败
				return false ;
			}else if(wantFileName!=null&&localFileNameArray==null){//当本地没有已下载的文件
				return true ;
			}else if(wantFileName!=null&&localFileNameArray!=null){//当要下载的文件在本地还没有
				if(localFileNameArray.length>0){
					for(int i=0; i<localFileNameArray.length; i++){
						if(localFileNameArray[i].equals(wantFileName+".zip")){
							return false ;
						}
					}
					return true ;
				}else{
					return true ;
				}
			}else{
				return false ;
			}
	}
	public static void main(String args[]){
		try {
			FtpZipOption.downLoadZipFile() ;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
 
分享到:
评论
1 楼 kong_bai 2009-02-24  
不错,很好用,有没想过实现断点续传?

相关推荐

    C# 如何实现FTP的上传和下载.zip

    FTP的上传下载功能 视频演示:https://space.bilibili.com/1624771

    C#实现FTP操作和Zip压缩操作

    实现浏览本地文件,本地文件的压缩和解压缩,本地文件单个和批量上传到服务器,并且可以选择上传到FTP服务器的目的目录,FTP服务器文件分级浏览,ftp服务器上文件单个和批量下载到本地指定目录,FTP服务器上新建...

    FTP,SFTP文件上传,下载到服务器,ZIP文件压缩,加密,解密,然后再上传到服务器,各种封装操作;

    FTP,SFTP文件上传,下载到服务器,ZIP文件压缩,加密,解密,然后再上传到服务器,各种封装操作; 里面包含了帮助类库和测试使用说明,下载即可运行;该代码是本人项目实际运行后的总结,分享给大家;

    WebFTP(支持ZIP在线解压) v3.6.2.rar

    文件:剪切、复制、粘贴、删除、压缩(ZIP解压、预览)、打包下载、权限设置、代码编辑(支持15种语言语法高亮)... 其他:图片预览、列表视图风格切换、文件列表排序、常用快捷键支持、批量文件上传... 使用说明 ...

    c#常用类库源码excel导入导出的Json类库条码类库加密解密ftp上传图片上传压缩解压汉子内码缓存等.zip

    c#常用类库大全源码,有excel导入导出的,Json类库,条码类库,加密解密,ftp上传,图片上传,压缩解压,汉子内码,缓存等。 BarCodeToHTML.cs CacheHelper.cs Captcha.cs CNDate.cs ConvertJson.cs CsvHelper.cs ...

    ftp在线解压与压缩程序

    ftp在线解压与压缩程序 可在线解压你上传的压缩文件 也可以压缩你的ftp文件

    FTP在线压缩解压工具

    程序会在“ZIP文档”处自动列出压缩包,点击“解压”即可 6,注意事项 (1)请不要使用太大的压缩包,一般服务器解压8MB以内的压缩包应该没有问题 (2)在非Windows环境下将压缩包解压以后若所解压的程序的安装使用出现...

    在线解压、压缩ZIP文件程序 V1.0

    使用方法:把zip文件通过FTP上传到本文件相同的目录下,选择zip文件;或直接点击“浏览...”上传zip文件。 解压的结果保留原来的目录结构。 默认验证密码: 123456 ,使用前请更改该密码(在源文件的开始部分) ...

    AspxZip在线压缩解压ZIP文档 v2.0.zip

    但由于他们的工作原理都是通过调用 RAR.exe 或 7Zip.exe 第三方压缩/解压程序进行 压缩/解压操作的,只要服务器的安全设置设得比较好,Web程序就无法调用 RAR.exe 等程序而不能使用,所以通用性不强,大部分的虚拟...

    java zip rar(区分有无密码的RAR文件) gz ftp工具类

    java项目中常使用到的工具类:zip压缩解压缩、rar解压(有密码的文件)、gz解压、FTP上传与下载

    AMFTP (FTP) 2.0.zip

    FTP上传管理工具 - AMFTP AMFTP - WEB FTP管理客户端 ...04) 压缩: Linux 环境全面支持 zip tar gzip(tar.gz) 格式解压与压缩。 05) 权限: 支持在线全面设置文件权限属性、同时支持应用到所有子目录和文件。

    AspxZip在线压缩解压ZIP文档 2.0.rar

    但由于他们的工作原理都是通过调用 RAR.exe 或 7Zip.exe 第三方压缩/解压程序进行 压缩/解压操作的,只要服务器的安全设置设得比较好,Web程序就无法调用 RAR.exe 等程序而不能使用,所以通用性不强,大部分的虚拟...

    AMFTP (FTP) v2.0.zip

    FTP上传管理工具 - AMFTP AMFTP - WEB FTP管理客户端 ...04) 压缩: Linux 环境全面支持 zip tar gzip(tar.gz) 格式解压与压缩。 05) 权限: 支持在线全面设置文件权限属性、同时支持应用到所有子目录和文件。

    ftp上传程序web版 net2ftp

    一款web版ftp上传程序,比客户端ftp软件软件快多了,压缩zip的网页文件上传后自动解压

    文档解压缩工具 WinZip 20.0 中文免费版.zip

    – FTP 上传新建和现有 Zip 文件 新增 – 邮寄 Zip 文件和 WinZip 作业完成日志 新增 – 从最新工作列表中直接运行 WinZip 工作 新增 – 从你的 Zip工件中直接查看压缩的图像 新增 – 预定义数据备份作业 – 创建...

    php在线解压ZIP文件程序

    php轻松实现在线解压ZIP文件程序,使用方法:把zip文件通过FTP上传到本文件相同的目录下,选择zip文件;或直接点击“浏览...”上传zip文件。

    net2ftp v1.0多国语言版.zip

    net2ftp是一个基于web的FTP服务,只要有浏览器,不必装任何客户端就可以随时进行...*上传自解压文件(zip, tar, tgz, gz) *搜索字符串或句子 *计算文件及文件夹的大小 前台首页界面演示图   后台管理界面演示图

    Oracle P/L SQL实现文件压缩、解压功能

    Oracle P/L SQL实现文件压缩、解压功能,以下是此过程包的头部,包体经常打包处理plb,感兴趣用户可以下载下来。 Create or Replace Package UTL_ZIP AUTHID CURRENT_USER as Type File_List is Table of Clob; -...

    JAVA处理FTP上的文件

    JAVA从FTP上取文件,解压文件,备份文件,读文件CSV文件,写文件,压缩文件等一系列操作FTP文件全部代码。

Global site tag (gtag.js) - Google Analytics