file相关的操作,(md5,word转html,复制,删除等)

package cn.edu.hbcf.common.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.ConnectException;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.hbcf.common.springmvc.CustomizedPropertyConfigurer;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class FileDigest {
    private static final Logger logger = LoggerFactory.getLogger(FileDigest.class);

    /**
     * 获取单个文件的MD5值!
     * 
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            return getFileMD5(in);
        } catch (Exception e) {
            logger.error("IOException: ", e);
            return null;
        }
    }

    /**
     * 获取单个文件的MD5值!
     * 
     * @param file
     * @return
     */
    public static String getFileMD5(InputStream in) {
        MessageDigest digest = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
        } catch (Exception e) {
            logger.error("IOException: ", e);
            return null;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("IOException: ", e);
            }
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16).toUpperCase();
    }

    /**
     * 获取文件夹中文件的MD5值
     * 
     * @param file
     * @param listChild
     *            ;true递归子目录中的文件
     * @return
     */
    public static Map<String, String> getDirMD5(File file, boolean listChild) {
        if (!file.isDirectory()) {
            return null;
        }
        // <filepath,md5>
        Map<String, String> map = new HashMap<String, String>();
        String md5;
        File files[] = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isDirectory() && listChild) {
                map.putAll(getDirMD5(f, listChild));
            } else {
                md5 = getFileMD5(f);
                if (md5 != null) {
                    map.put(f.getPath(), md5);
                }
            }
        }
        return map;
    }
    
    
    
    
    /**
     * 文件转化为字节数组
     * 
     * @param file
     * @return
     */
    public static byte[] getBytesFromFile(File file) {
        byte[] ret = null;
        try {
            if (file == null) {
                // log.error("helper:the file is null!");
                return null;
            }
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            byte[] b = new byte[4096];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            in.close();
            out.close();
            ret = out.toByteArray();
        } catch (IOException e) {
            // log.error("helper:get bytes from file process error!");
            e.printStackTrace();
        }
        return ret;
    }
    
    /**
     * 把字节数组保存为一个文件
     * 
     * @param b
     * @param outputFile
     * @return
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        File ret = null;
        BufferedOutputStream stream = null;
        try {
            ret = new File(outputFile);
            if(ret.exists()){
                ret.delete();
            }
            FileOutputStream fstream = new FileOutputStream(ret);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            // log.error("helper:get file from byte process error!");
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    // log.error("helper:get file from byte process error!");
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    
    /**
     * 将word文档转换成html文档
     * 
     * @param docFile
     *                需要转换的word文档
     * @param filepath
     *                转换之后html的存放路径
     * @return 转换之后的html文件
     */
    public static File convert(File docFile, File htmlFile) {
        // 创建Openoffice连接
        OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
        try {
            // 连接
            con.connect();
        } catch (ConnectException e) {
            System.out.println("获取OpenOffice连接失败...");
            e.printStackTrace();
        }
        // 创建转换器
        DocumentConverter converter = new OpenOfficeDocumentConverter(con);
        // 转换文档问html
        converter.convert(docFile, htmlFile);
        // 关闭openoffice连接
        con.disconnect();
        return htmlFile;
    }
    private static final int BUFFEREDSIZE = 1024;
    /**
      * 解压zip或者rar包的内容到指定的目录下,可以处理其文件夹下包含子文件夹的情况
      *
      * @param zipFilename
      *            要解压的zip或者rar包文件
      * @param outputDirectory
      *            解压后存放的目录
      *
      */
    public static void unzip(String zipFilename, String outputDirectory)
               throws Exception {
        File outFile = new File(outputDirectory);
        if (!outFile.exists()) {
            outFile.mkdirs();
          }
        ZipFile zipFile = new ZipFile(zipFilename,"gbk");
        Enumeration en = zipFile.getEntries();
        ZipEntry zipEntry = null;
        InputStream in = null;
        FileOutputStream out = null;
        while (en.hasMoreElements()) {
             zipEntry = (ZipEntry) en.nextElement();
             if (zipEntry.isDirectory()) {
                // mkdir directory
                String dirName = zipEntry.getName();
                dirName = dirName.substring(0, dirName.length() - 1);
                File f = new File(outFile.getPath() + File.separator + dirName);
                f.mkdirs();
             }else {
                //unzip file
                String strFilePath = outFile.getPath() + File.separator
                  + zipEntry.getName();
                File f = new File(strFilePath);
                //判断文件不存在的话,就创建该文件所在文件夹的目录
                if (!f.exists()) {
                     String[] arrFolderName = zipEntry.getName().split("/");
                     String strRealFolder = "";
                     for (int i = 0; i < (arrFolderName.length - 1); i++) {
                      strRealFolder += arrFolderName[i] + File.separator;
                     }
                     strRealFolder = outFile.getPath() + File.separator
                       + strRealFolder;
                     File tempDir = new File(strRealFolder);
                     //此处使用.mkdirs()方法,而不能用.mkdir()
                     tempDir.mkdirs();
                }
                try {
                    f.createNewFile();
                    in = zipFile.getInputStream(zipEntry);
                    out = new FileOutputStream(f);
                     int c;
                     byte[] by = new byte[BUFFEREDSIZE];
                     while ((c = in.read(by)) != -1) {
                      out.write(by, 0, c);
                     }
                } catch (Exception e) {
                    throw e;
                }finally{
                    if(out!=null)
                        out.close();
                    if(in!=null)
                     in.close();
                }
                 
              }
             }
        zipFile.close();
    }
    
    /**
     * 删除目录(文件夹)以及目录下的文件
     * @param   sPath 被删除目录的文件路径 
     * @return  目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
       boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
    /**       
     * 将1个RAR文件解压    
     * rarFileName 需要解压的RAR文件(必须包含路径信息以及后缀)       
     * destDir 解压后的文件放置目录     
     * @throws IOException 
     */  
    public static void unRARFile(String rarFileName, String destDir) throws IOException {           
        String unrarCmd =(String) CustomizedPropertyConfigurer
                .getContextProperty("rarUrl");
//        String unrarCmd ="C:\\soft\\WinRAR\\UnRAR.exe x ";
        unrarCmd= "\""+unrarCmd +"\" x \""+rarFileName + "\" \"" + destDir+"\"";           
        Runtime rt = Runtime.getRuntime();               
        rt.exec(unrarCmd);            
    }  
    /**
     * 复制文件
     * @param s输入
     * @param t输出
     */
    public static void fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
    
}

 

posted @ 2015-11-06 15:35  花语苑  阅读(462)  评论(0编辑  收藏  举报