用java进行文件迁移

package com.y.d.x.fileget;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class GetFile {
	/*便利指定文件夹下的
	 * @param path 文件夹路径
	 */
	private static final int SIZE = 1024;
	public static void traverseFolder2(String path,String name) throws IOException {
       //获取路径文件
		
        File file = new File(path);
        if (file.exists()) {
        	//获取目录下所有的子文件
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件是空的!");
                return;
            } else {
            	//便利文件列表
                for (File file2 : files) {
                	//如果是路径,就输入的目标文件路径创建目标路径
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        String pathresult=file2.getAbsolutePath();
                        //分析路径产生文件夹路径
                    	pathresult=pathresult.substring(0, pathresult.indexOf("\\", 2)+1).concat(name).concat(pathresult.substring((pathresult.indexOf("\\", 2)+1+name.length()),pathresult.length()));
                    	File resultFile=new File(pathresult);
                    	//不存在路径
                    	if(!resultFile.exists())
                    	{
                    	    //创建路径
                    		resultFile.mkdirs();
                    	}
                    	traverseFolder2(file2.getAbsolutePath(),"log2");
                    } //如果是文件,就按照路径创建文件,并把文件进行读取写入操作
                    else {
                    	String pathresult=file2.getAbsolutePath();
                    	//分析路径产生文件目标路径
                    	pathresult=pathresult.substring(0, pathresult.indexOf("\\", 2)+1).concat(name).concat(pathresult.substring((pathresult.indexOf("\\", 2)+1+name.length()),pathresult.length()));
                    	System.out.println("pathresult"+pathresult);
                    	try {
                    		File resultFile=new File(pathresult);
							FileInputStream fis = new FileInputStream(file2) ;
							FileOutputStream fos=new FileOutputStream(resultFile);
							 int len = 0;  
						     byte[] buf = new byte[SIZE];
						     while((len=fis.read(buf , 0, buf.length))!=-1){  
						    	 fos.write(buf,0,len); 
						        }  
						       try{
	                    		 fis.close();  
	                             fos.close(); 
	                    		}catch(Exception e)
	                    		{
	                    			System.out.println("流关闭错误"+e);
	                    		}
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}finally { 
                    		
                    	}
                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			traverseFolder2("D:\\log1","log2");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

需要将系统的一些附件,迁移到另外一台亚马逊服务器

package fileget;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.slf4j.LoggerFactory;
import com.gc.annuity.common.util.*;
import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.exception.RarException.RarExceptionType;
import com.github.junrar.rarfile.FileHeader;
import com.neusoft.fdframework.core.ServiceException;


public class SyncToYaMAXunFile {
	/*利用
	 * @param path 文件夹路径
	 * 上传到亚马逊服务器
	 */
	private static final int SIZE = 1024;
	static int i=0;
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ZipCompressorUtil.class);
	
	public static void traverseFolder(String path) throws IOException {
	       //获取路径文件
			
	        File file = new File(path);
	        if (file.exists()) {
	        	//获取目录下所有的子文件
	            File[] files = file.listFiles();
	            if (files.length == 0) {
	                System.out.println("文件是空的!");
	                return;
	            } else {
	            	//便利文件列表
	                for (File file2 : files) {
	                	//如果是路径,就递归
	                    if (file2.isDirectory()) {
	                        System.out.println("文件夹:" + file2.getAbsolutePath());
	                    	traverseFolder(file2.getAbsolutePath());
	                    } //如果是文件,上传作
	                    else {
	                    	//源路径
	                    	String pathresult=file2.getAbsolutePath();
	                    	//目标路径
	                    	String resultName=null;
	                    	//分析上传路径获取文件名
	                    	String fileName=pathresult.substring(pathresult.lastIndexOf("\\")+1, pathresult.length());
	                    	/**
	                    	 * 不解析上传
	                    	 */
	                    	resultName=pathresult.replace("\\", "/");
	                    	resultName=resultName.substring(resultName.indexOf(":/")+2,resultName.length());
	                    	/*
	                    	 * 解析后上传
	                    	 * //zip文件直接上传
	                    	if(fileName.endsWith(".zip")||fileName.endsWith(".rar"))
	                    	{
	                    		resultName=fileName;
	                    	}
	                    	//非zip文件
	                    	else{
	                    		//附件名为:客户号_保全申请号.XX形式的
	                    		if(fileName.contains("_"))
	                    		{
	                    			//构造亚马逊服务器上的文件夹--取保全申请号为文件夹名称
			                    	 String directoryName=fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
			                    	 //拼接亚马逊服务器完整的路径
			                    	 resultName=directoryName.concat("/").concat(fileName);
	                    		}
	                    		//附件名为:被保险人客户号.XX
	                    		else{
	                    			//构造亚马逊服务器上的文件夹--取被保险人客户号为文件夹名称
			                    	 String directoryName=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.lastIndexOf("."));
			                    	 //拼接亚马逊服务器完整的路径
			                    	 resultName=directoryName.concat("/").concat(fileName);
	                    		}
		                    	
	                    	}*/
	                    	//调用S3接口上传到亚马逊服务器  resultName亚马逊服务器存放路径,会自动创建覆盖,file2为本地文件的路径类型File
	                    	S3Store s3=new S3Store();
	                    	s3.uploadObject(file2, resultName);
	                    	System.out.println("第"+(i++)+"条数据  ----------上传服务器地址:" + resultName);
	                    	s3=null;
	                    }
	                }
	            }
	        } else {
	            System.out.println("文件不存在!");
	        }
	    }
	/**
	 * 删除亚马逊服务器文件1
	 * @param path
	 * @throws IOException
	 */
	public static void deleteFolder1(String path) throws IOException {
		 //获取路径文件
		
        File file = new File(path);
        if (file.exists()) {
        	//获取目录下所有的子文件
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件是空的!");
                return;
            } else {
            	//便利文件列表
                for (File file2 : files) {
                	//如果是路径,就递归
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        deleteFolder1(file2.getAbsolutePath());
                    } //如果是文件,上传作
                    else {
                    	//源路径
                    	String pathresult=file2.getAbsolutePath();
                    	//目标路径
                    	String resultName=null;
                    	//分析上传路径获取文件名
                    	String fileName=pathresult.substring(pathresult.lastIndexOf("\\")+1, pathresult.length());
                    	/**
                    	 * 不解析上传
                    	 */
                    	resultName=pathresult;
                    	//
                    	/*
                    	 * 解析后上传
                    	 * //zip文件直接上传
                    	if(fileName.endsWith(".zip")||fileName.endsWith(".rar"))
                    	{
                    		resultName=fileName;
                    	}
                    	//非zip文件
                    	else{
                    		//附件名为:客户号_保全申请号.XX形式的
                    		if(fileName.contains("_"))
                    		{
                    			//构造亚马逊服务器上的文件夹--取保全申请号为文件夹名称
		                    	 String directoryName=fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
		                    	 //拼接亚马逊服务器完整的路径
		                    	 resultName=directoryName.concat("/").concat(fileName);
                    		}
                    		//附件名为:被保险人客户号.XX
                    		else{
                    			//构造亚马逊服务器上的文件夹--取被保险人客户号为文件夹名称
		                    	 String directoryName=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.lastIndexOf("."));
		                    	 //拼接亚马逊服务器完整的路径
		                    	 resultName=directoryName.concat("/").concat(fileName);
                    		}
	                    	
                    	}*/
                    	//调用S3接口上传到亚马逊服务器  resultName亚马逊服务器存放路径,会自动创建覆盖,file2为本地文件的路径类型File
                    	S3Store s3=new S3Store();
                    	s3.deleteObject(resultName);
                    	System.out.println("删除"+(i++)+"条数据  ----------上传服务器地址:" + resultName);
                    	s3=null;


                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
	    }
	/**
	 * 删除亚马逊服务器文件
	 * @param path
	 * @throws IOException
	 */
	public static void deleteFolder(String path) throws IOException {
	       //获取路径文件
			
	        File file = new File(path);
	        if (file.exists()) {
	        	//获取目录下所有的子文件
	            File[] files = file.listFiles();
	            if (files.length == 0) {
	                System.out.println("文件是空的!");
	                return;
	            } else {
	            	//便利文件列表
	                for (File file2 : files) {
	                	//如果是路径,就递归
	                    if (file2.isDirectory()) {
	                        System.out.println("文件夹:" + file2.getAbsolutePath());
	                        deleteFolder(file2.getAbsolutePath());
	                    } //如果是文件,上传作
	                    else {
	                    	//源路径
	                    	String pathresult=file2.getAbsolutePath();
	                    	//目标路径
	                    	String resultName=null;
	                    	//分析上传路径获取文件名
	                    	String fileName=pathresult.substring(pathresult.lastIndexOf("\\")+1, pathresult.length());
	                    	//非zip文件
	                    	
	                    		//附件名为:客户号_保全申请号.XX形式的
	                    		if(fileName.contains("_"))
	                    		{
	                    			//构造亚马逊服务器上的文件夹--取保全申请号为文件夹名称
			                    	 String directoryName=fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
			                    	 //拼接亚马逊服务器完整的路径
			                    	 resultName=directoryName.concat("/").concat(fileName);
	                    		}
	                    		//附件名为:被保险人客户号.XX
	                    		else{
	                    			//构造亚马逊服务器上的文件夹--取被保险人客户号为文件夹名称
			                    	 String directoryName=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.lastIndexOf("."));
			                    	 //拼接亚马逊服务器完整的路径
			                    	 resultName=directoryName.concat("/").concat(fileName);
	                    		}
		                    	
	                    	
	                    	//调用S3接口上传到亚马逊服务器  resultName亚马逊服务器存放路径,会自动创建覆盖,file2为本地文件的路径类型File
	                    	S3Store s3=new S3Store();
	                    	s3.deleteObject(resultName);
	                    	System.out.println("删除"+(i++)+"条数据  ----------上传服务器地址:" + resultName);
	                    	s3=null;
	                    }
	                }
	            }
	        } else {
	            System.out.println("文件不存在!");
	        }
	    }
	/**
	 * 递归解压所有zip包
		 * @param path
	 * @throws IOException
	 */
	public static void zipAndRarDecmprs(String path) throws IOException {
	       //获取路径文件
	        File file = new File(path);
	        if (file.exists()) {
	        	//获取目录下所有的子文件
	            File[] files = file.listFiles();
	            if (files.length == 0) {
	                System.out.println("文件是空的!");
	                return;
	            } else {
	            	//便利文件列表
	                for (File file2 : files) {
	                	//如果是路径,就递归
	                    if (file2.isDirectory()) {
	                        System.out.println("文件夹:" + file2.getAbsolutePath());
	                        zipAndRarDecmprs(file2.getAbsolutePath());
	                    } //如果是文件,上传作
	                    else {
	                    	//压缩包源路径
	                    	String pathresult=file2.getAbsolutePath();
	                    	//分析压缩包获取文件名
	                    	String fileName=pathresult.substring(pathresult.lastIndexOf("\\")+1, pathresult.length());
	                    	//zip解压缩
	                    	if(fileName.endsWith(".zip"))
	                    	{
	                    		logger.info("解压缩zip文件开始"+new Date(System.currentTimeMillis()).toLocaleString());
	                    		zipDecompression(pathresult);
	                    		logger.info("解压缩zip文件结束"+new Date(System.currentTimeMillis()).toLocaleString());
	                    	}
	                    	//rar解压缩
	                    	else if(fileName.endsWith(".rar"))
	                    	{   
	                    		logger.info("解压缩rar文件开始"+ new Date(System.currentTimeMillis()).toLocaleString());
	                    		rarDecompression(pathresult);
	                    		logger.info("解压缩rar文件结束"+ new Date(System.currentTimeMillis()).toLocaleString());
	    	                    
	                    	}
	                    }
	                }
	            }
	         //可在此调用删除压缩包   
	           zipAndRarRemove(path);
	        } else {
	            System.out.println("文件不存在!");
	        }
	    }
	/**
	 * 递归删除所有zip包
		 * @param path
	 * @throws IOException
	 */
	public static void zipAndRarRemove(String path) throws IOException {
	       //获取路径文件
			
	        File file = new File(path);
	        if (file.exists()) {
	        	//获取目录下所有的子文件
	            File[] files = file.listFiles();
	            if (files.length == 0) {
	                System.out.println("文件是空的!");
	                return;
	            } else {
	            	//便利文件列表
	                for (File file2 : files) {
	                	//如果是路径,就递归
	                    if (file2.isDirectory()) {
	                        System.out.println("文件夹:" + file2.getAbsolutePath());
	                        zipAndRarRemove(file2.getAbsolutePath());
	                    } //如果是文件,上传作
	                    else {
	                    	//源路径
	                    	String pathresult=file2.getAbsolutePath();
	                    	//分析上传路径获取文件名
	                    	String fileName=pathresult.substring(pathresult.lastIndexOf("\\")+1, pathresult.length());
	                    	//zip文件直接上传
	                    	if(fileName.endsWith(".zip")||fileName.endsWith(".rar"))
	                    	{   
	                    		System.out.println("开始删除zip,rar文件"+file2.toString());
	                    		file2.delete();	
	                    	}
	                    }
	                }
	            }
	        } else {
	            System.out.println("文件不存在!");
	        }
	    }
	/**
	 * 解压缩rar文件
	 * @param rarFileName
	 * @param outFilePath
	 * @return
	 */
	public static Boolean rarDecompression(String rarFileName)
    {     
		//要解压到的目标地址
		String outFilePath=rarFileName.substring(0,rarFileName.lastIndexOf("."));
		 boolean flag = false;  
         try  {    
        	 //获取到rar压缩包
             Archive archive = new  Archive(new File(rarFileName));    
             if(archive == null){  
                 throw new FileNotFoundException(rarFileName + " NOT FOUND!");  
             }  
             if(archive.isEncrypted()){  
                 throw new Exception(rarFileName + " IS ENCRYPTED!");  
             }  
             //获取到rar压缩包中的所有的文件
             List<FileHeader> files =  archive.getFileHeaders();  
             for (FileHeader fh : files) {  
                     if(fh.isEncrypted()){  
                         throw new Exception(rarFileName + " IS ENCRYPTED!");  
                     }   
                     //只获取文件名
                     String fileName = fh.getFileNameW();
                     //如果压缩包中存放的是路径,不是一个具体的文件,就跳过(如果在)
                     if(!fileName.contains("."))
                    	 continue;
                     if(fileName != null && fileName.trim().length() > 0){  
                         String saveFileName = outFilePath+"\\"+fileName;  
                         File saveFile = new File(saveFileName);  
                         File parent =  saveFile.getParentFile();
                         //按照压缩包中的文件创建深一层文件夹
                         if(!parent.exists()){  
                             parent.mkdirs();  
                         }  
                         if(!saveFile.exists()){  
                             saveFile.createNewFile();  
                         }  
                         //获取输出流
                         FileOutputStream fos = new FileOutputStream(saveFile);  
                         try {   
                        	 //填充将fh和输出流fos进行输出
                             archive.extractFile(fh, fos);   
                             fos.flush();  
                             fos.close();
                             archive.close();
                         } catch (RarException e) {   
                             if(e.getType().equals(RarExceptionType.notImplementedYet)){   
                             }   
                         }finally{   
                        	 fos.flush();  
                             fos.close();
                             //不关闭的话后续无法删除该文件
                             archive.close();
                         }   
                     }  
             }  
             flag = true;  
         } catch  (Exception e) {  
             e.printStackTrace();  
            
         }    
         return flag;  
    }
/**
 * 解压zip包
 * @param path  zip包的路径
 * @return
 */
	 public static String zipDecompression(String path)
	    {
		    //获取包含zip包名的路径,即.zip之前的路径
	        String dirpath = path.substring(0, path.lastIndexOf(".")) + File.separator;
	       /**
	        * 如果不存在该路径,就创建
	        */
	        File dir = new File(dirpath);
	        if (!dir.exists())
	        {  
	            dir.mkdirs();
	        }
	        //用于判断是否读入数据流
	        int count = -1;
	        File file = null;
	        InputStream is = null;
	        FileOutputStream fos = null;
	        BufferedOutputStream bos = null;
	        ZipFile zipFile = null;
	        try
	        {   /**
	             * 读取zip文件转化为枚举类型
	             */
	            zipFile = new ZipFile(path, Charset.forName("GBK"));
	            Enumeration<? extends ZipEntry> entries = zipFile.entries();
                //便利entries
	            while (entries.hasMoreElements())
	            {
	                byte buf[] = new byte[SIZE];
	                ZipEntry entry = (ZipEntry) entries.nextElement();
                    //获取压缩包中的文件名
	                String filename = entry.getName();
	                boolean ismkdir = false;
	                //如果压缩包中读取的为路径
	                if (filename.lastIndexOf("/") != -1)
	                {
	                    ismkdir = true;
	                }
	                //构建路径名称
	                filename = dirpath + filename;
                    //目录
	                if (entry.isDirectory())
	                {
	                    file = new File(filename);
	                    file.mkdirs();
	                    continue;
	                }
	                file = new File(filename);
	                if (!file.exists())
	                {
	                    if (ismkdir)
	                    {
	                        new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs(); 
	                    }
	                }
	                
	                file.createNewFile(); //创建文件  


	                is = zipFile.getInputStream(entry);
	                fos = new FileOutputStream(file);
	                bos = new BufferedOutputStream(fos, SIZE);


	                while ((count = is.read(buf)) > -1)
	                {
	                    bos.write(buf, 0, count);
	                }
	                bos.flush();
	                bos.close();
	                fos.close();


	                is.close();
	            }
	            zipFile.close();


	        }
	        catch (IOException e)
	        {
	            logger.info("GCA00071:" + e.getMessage());
	            throw new ServiceException("GCA00071");
	        }
	        finally
	        {
	            try
	            {
	                if (bos != null)
	                {
	                    bos.close();
	                }
	                if (fos != null)
	                {
	                    fos.close();
	                }
	                if (is != null)
	                {
	                    is.close();
	                }
	                if (zipFile != null)
	                {
	                    zipFile.close();
	                }
	            }
	            catch (Exception e)
	            {
	                logger.info("GCA00071:" + e.getMessage());
	            }
	        }
	        return dirpath;
	    }


	public static void traverseLocal(String path,String name) throws IOException {
       //获取路径文件
        File file = new File(path);
        if (file.exists()) {
        	//获取目录下所有的子文件
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件是空的!");
                return;
            } else {
            	//便利文件列表
                for (File file2 : files) {
                	//如果是路径,就输入的目标文件路径创建目标路径
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        String pathresult=file2.getAbsolutePath();
                        //分析路径产生文件夹路径
                    	pathresult=pathresult.substring(0, pathresult.indexOf("\\", 2)+1).concat(name).concat(pathresult.substring((pathresult.indexOf("\\", 2)+1+name.length()),pathresult.length()));
                    	File resultFile=new File(pathresult);
                    	//不存在路径
                    	if(!resultFile.exists())
                    	{
                    	    //创建路径
                    		resultFile.mkdirs();
                    	}
                    	traverseLocal(file2.getAbsolutePath(),"log2");
                    } //如果是文件,就按照路径创建文件,并把文件进行读取写入操作
                    else {
                    	String pathresult=file2.getAbsolutePath();
                    	//分析路径产生文件目标路径
                    	pathresult=pathresult.substring(0, pathresult.indexOf("\\", 2)+1).concat(name).concat(pathresult.substring((pathresult.indexOf("\\", 2)+1+name.length()),pathresult.length()));
                    	System.out.println("pathresult"+pathresult);
                    	try {
                    		File resultFile=new File(pathresult);
							FileInputStream fis = new FileInputStream(file2) ;
							FileOutputStream fos=new FileOutputStream(resultFile);
							 int len = 0;  
						     byte[] buf = new byte[SIZE];
						     while((len=fis.read(buf , 0, buf.length))!=-1){  
						    	 fos.write(buf,0,len); 
						        }  
						       try{
	                    		 fis.close();  
	                             fos.close(); 
	                    		}catch(Exception e)
	                    		{
	                    			System.out.println("流关闭错误"+e);
	                    		}
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}finally { 
                    		
                    	}
                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			//解压所有zip,rar包
			//zipAndRarDecmprs("D:/log1");
			//删除所有zip rar包
			//zipAndRarRemove("D:/log1");
			traverseFolder("E:\\upload");
			//traverseFolder("E:\\uploadCertificatePhoto");
			//traverseFolder("E:\\uploadCertificateZip");
			//traverseFolder("E:\\uploadDeathPhoto");
			//deleteFolder("E:\\uploadDeathPhoto");
			//deleteFolder1("E:\\upload");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


}



猜你喜欢

转载自blog.csdn.net/xuedengyong/article/details/79195895
今日推荐