FileUtil文件工具类

文件处理工具类,内包括文件的上传下载、拷贝、压缩到zip


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

/**
 * 文件工具类
 * @author
 *
 */
@Component
public class FileUtil
{
	/*匹配${}的正则,还有分组的概念*/
	private Pattern escapresource = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
	
//MD5加密
	 private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
	            "e", "f" };		
//------------------------MD5加密开始---------------------------------------------
	/**
     * @param source
     *            需要加密的原字符串
     * @param encoding
     *            指定编码类型
     * @param uppercase
     *            是否转为大写字符串
     * @return
     */
    public static String MD5Encode(String source, String encoding, boolean uppercase) {
    
        String result = null;
        try {
            result = source;
            // 获得MD5摘要对象
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 使用指定的字节数组更新摘要信息
            messageDigest.update(result.getBytes(encoding));
            // messageDigest.digest()获得16位长度
            result = byteArrayToHexString(messageDigest.digest());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return uppercase ? result.toUpperCase() : result;
    }
    /**
     * 转换字节数组为16进制字符串
     * 
     * @param bytes
     *            字节数组
     * @return
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte tem : bytes) {
            stringBuilder.append(byteToHexString(tem));
        }
        return stringBuilder.toString();
    }

    /**
     * 转换byte到16进制
     * 
     * @param b
     *            要转换的byte
     * @return 16进制对应的字符
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
	
//------------------------MD5加密结束---------------------------------------------
	/**
	 * 对图片和视频进行Base64编码
	 */
	public static String strToBase64(String string)
	{
		String encodeBase64String = null;
		try
		{
			// 加密
			byte[] buffer = null;

			File file = new File(string);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1)
			{
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
			encodeBase64String = Base64.encodeBase64String(buffer);
		} catch (Exception e)
		{
			e.printStackTrace();
		} 
		return encodeBase64String;
	}
	
	/**
	 * 读取输入流中的内容
	 * @param is
	 * @return	返回值为字符串
	 */
	public String readFile(InputStream is)
	{
		StringBuffer sb = new StringBuffer() ; 
		/* 异常是:选中合适的代码;alt + shift + z */
		try
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(is, ConstatFinalUtil.CHARSET));
			String line = ""; 
			while((line = br.readLine()) != null)
			{
				sb.append(line);
			}
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return sb.toString() ; 
	}
	
	/**
	 * 存储内容到配置文件中
	 * @param os
	 * @param content
	 * @throws IOException
	 */
	public void writeFile(OutputStream os, String content)  
            throws IOException 
	{
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,ConstatFinalUtil.CHARSET));
		bw.write(content);
		bw.flush();
        bw.close();  
    }  
  
	/**
	 * 拷贝文件,参数是文件对象,不再是管子 
	 * 
	 * @param souFile
	 * @param tarFile
	 * @return
	 */
	public boolean copy(File souFile , File tarFile)
	{
		try
		{
			FileInputStream fis = new FileInputStream(souFile);
			FileOutputStream fos = new FileOutputStream(tarFile);
			return this.copy(fis, fos,true) ;
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		return false ; 
	}
	
	/**
	 * 拷贝文件
	 * @return
	 */
	public boolean copy(InputStream is , OutputStream os , boolean closeFlag)
	{
		/* 拷贝的时候,带上粗管子 */
		BufferedInputStream bis = new BufferedInputStream(is);
		BufferedOutputStream bos = new BufferedOutputStream(os);
		
		/* 准备容器
		 * 1024 * 1024 * 2 === 2m
		 *  */
		byte[] b = new byte[2 * 1024 * 1024];
		int len = 0 ;
		try
		{
			while((len = bis.read(b)) != -1)
			{
				bos.write(b, 0, len);
			}
			/* 写数据缓存 */
			bos.flush();
			/* 拷贝完成,返回true */
			return true ; 
		} catch (IOException e)
		{
			e.printStackTrace();
		}finally
		{
			if(closeFlag)
			{
				try
				{
					if(is != null)
					{
						is.close();
						is = null; 
					}
				} catch (IOException e)
				{
					e.printStackTrace();
				}
				try
				{
					if(os != null)
					{
						os.close();
						os = null ;
					}
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return false ; 
	}
	
	/**
	 * 专门用来处理点位符
	 * @return
	 */
	public String replaceOperator(String source , Map<String, String> paramsMap)
	{
		if(paramsMap.size() == 0 )
		{
			return source ; 
		}
		
		StringBuffer sb = new StringBuffer();
		/*将${wangsh}的值替换掉*/
		Matcher matcher = this.escapresource.matcher(source);
		while(matcher.find())
		{
			if(paramsMap.get(matcher.group(2)) != null )
			{
				matcher.appendReplacement(sb, paramsMap.get(matcher.group(2))) ;
			}
		}
		
		/* 将尾巴加上去 */
		matcher.appendTail(sb);
		return sb.toString() ; 
	}
	
	/**
	 * 读取某个文件的内容
	 * 并且为对象赋值,类似于资源文件
	 * 如${wangsh},map中键为wangsh的值放的是yanglp,会将整个${wangsh}替换为yanglp
	 * 
	 * @param sourceFile
	 * @param charset
	 * @param paramsMap 键为源文件中出现的,值为真正要替换的值
	 * @return
	 */
	public String readFile(InputStream is , String charset ,
			Map<String, String> paramsMap)
	{
		if(charset == null || "".equalsIgnoreCase(charset))
		{
			charset = ConstatFinalUtil.CHARSET ; 
		}
		StringBuffer sb = new StringBuffer();
		try
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));
			String line = "" ; 
			StringBuffer patressb = new StringBuffer();
			while((line = br.readLine()) != null )
			{
				line = line.trim() ; 
				patressb.append(line);
			}
			sb.append(this.replaceOperator(patressb.toString(), paramsMap));
			br.close();
		} catch (IOException e)
		{
			ConstatFinalUtil.LOGGER.error("读取文件出错了", e);
		}
		return sb.toString() ; 
	}
	
	/**
	 * 压缩
	 * @param os 压缩文件的输出流
	 * @param souFileMap 要压缩的文件列表;键为压缩包中文件的名字,值为:输入流(要压缩的文件)
	 */
	public boolean zip(OutputStream os,Map<String, InputStream> souFileMap)
	{
		ZipOutputStream zos = new ZipOutputStream(os);
		try
		{
			/* 循环取出压缩文件列表 */
			for (Iterator<Entry<String, InputStream>> iterator = souFileMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry<String, InputStream> entry = iterator.next();
				String key = entry.getKey() ; 
				InputStream souFileIs = entry.getValue() ; 
				
				/* 压缩包里面的选项 */
				ZipEntry zipEntry = new ZipEntry(key);
				/* 将压缩包里面的内容放到压缩包中 */
				zos.putNextEntry(zipEntry);
				
				/* 拷贝文件 */
				this.copy(souFileIs, zos,false);
				/* 关闭文件 */
				souFileIs.close();
				/* 此文件结束 */
				zos.closeEntry();
				ConstatFinalUtil.LOGGER.info("====name:{}=",key);
			}
			return true ; 
		} catch (FileNotFoundException e)
		{
			ConstatFinalUtil.LOGGER.error("文件木有找到;", e);
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("读取文件出错了", e);
		}finally
		{
			try
			{
				if(zos != null)
				{
					zos.close();
					zos = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("关闭zos出错了", e);
			}
		}
		return false ; 
	}
	
	public static void main(String[] args)
	{
//		System.out.println("=======");
//		FileUtil fileUtil = new FileUtil() ; 
		/*File souFile = new File("d:/test/az.jpg");
		File tarFile = new File("d:/test/az_bak.jpg");
		fileUtil.copy(souFile, tarFile);*/
		
//		try
//		{
//			/* 压缩文件 */
//			OutputStream os = new FileOutputStream("d:/ya.zip");
//			Map souFileMap = new HashMap();
//			
//			souFileMap.put("1.jpg", new FileInputStream("d:/1.jpg"));
//			souFileMap.put("2.jpg", new FileInputStream("d:/2.jpg"));
//			souFileMap.put("3.jpg", new FileInputStream("d:/3.jpg"));
//			
//			boolean flag = fileUtil.zip(os, souFileMap);
//			ConstatFinalUtil.LOGGER.info("=压缩的结果==" + flag);
//		} catch (FileNotFoundException e)
//		{
//			e.printStackTrace();
//		}	
//		String  str = "adasda";	
//		String md5Encode = FileUtil.MD5Encode(str,"utf-8", false);
//	System.out.println(md5Encode);
//	
		
	}
}

你可能感兴趣的:(java-工具类)