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();
            }

        }

    }

}
时间: 2024-08-10 02:08:36

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

android + File相关操作

File相关的,有很多操作,比如写入.读出.判断文件.获取文件列表...等等 相关链接: http://blog.csdn.net/avi9111/article/details/6917187 //写的干净 http://blog.csdn.net/qianfu111/article/details/10054993 //function写的 不错

R语言文件相关的操作

1. 文件系统介绍 R语言对文件系统的操作,包括文件操作和目录操作,函数API都定义在base包中. 2. 目录操作 2.1 查看目录 查看当前目录下的子目录. # 启动R程序 ~ R # 当前的目录 > getwd() [1] "/home/conan/R/fs" # 查看当前目录的子目录 > list.dirs() [1] "." "./tmp" 查看当前目录的子目录和文件. > dir() [1] "readme

C#操作Office.word(二)

在上一篇文章"C#操作Office.word(一)"中我们讲述了如何使用VS2010引用COM中Miscrosoft Word 14.0 Object Library实现创建文档,而这篇文章将讲述如何添加表格和图片,因为我在C#联系数据库做销售系统中需要打印表单,,我想以图表形式显示在word中,同时生成相应的饼状图或柱状图,所以才有查阅了相关资料,完成文章,供大家分享.其中使用openFileDialog控件也是希望大家学习了解下. 一. 界面设置 在界面上增加一个按钮,点击这个按钮

Java操作Microsoft Word之jacob

转自: 现在我们一起来看看,用Java如何操作Microsoft Word. jacob,官网是http://danadler.com/jacob 这是一个开源的工具.最新版本1.7 官方的解释是:The JACOB Project: A JAva-COM Bridge 这是官方对下载文件的说明: jacob.jar: a JAR file for the java classes which you must add to your CLASSPATH. The package names r

MFC File相关命令流程分析

一个APP可以有多个文档模板,一个文档模板可以有多个文档(Document),一个Document可以有多个View.在程序.要在程序中添加新的文档模板可以如下所示: CSingleDocTemplate*pDocTemplate; pDocTemplate = newCSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CmfcArchiveDoc), RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口 RUNTIME_

Go语言学习之os包中文件相关的操作(The way to go)

生命不止,继续 go go go !!! 今天跟大家分享学习的是os package,主要是介绍一些跟文件或文件夹相关的操作. os包 Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values o

拷贝构造,深度拷贝,关于delete和default相关的操作,explicit,类赋初值,构造函数和析构函数,成员函数和内联函数,关于内存存储,默认参数,静态函数和普通函数,const函数,友元

 1.拷贝构造 //拷贝构造的规则,有两种方式实现初始化. //1.一个是通过在后面:a(x),b(y)的方式实现初始化. //2.第二种初始化的方式是直接在构造方法里面实现初始化. 案例如下: #include<iostream> //如果声明已经定义,边不会生成 class classA { private: int a; int b; public: //拷贝构造的规则,有两种方式实现初始化 //1.一个是通过在后面:a(x),b(y)的方式实现初始化 //2.第二种初始化的方式是直

算法—二叉查找树的相关一些操作及总结

二叉查找树得以广泛应用的一个重要原因就是它能够保持键的有序性,因此它可以作为实现有序符号表API中的众多方法的基础.这使得符号表的用例不仅能够通过键还能通过键的相对顺序来访问键值对.下面,我们要研究有序符号表API中各个方法的实现. 1.最大键和最小键 如果根结点的左链接为空,那么一棵二叉查找树中最小的键就是根结点:如果左链接非空,那么树中的最小键就是左子树中的最小键.简单的循环也能等价实现这段描述,但为了保持一致性我们使用了递归.找出最大键的方法也是类似的,只是变为查找右子树而已. 2.向上取

[Word]解决Word中执行输入操作时后面字符自动被删除的问题

问题分析:这是由于当前输入方式为"改写",在此方式下,如果某个位置处后面有其他字符,当在此位置执行输入操作时,就会默认删除其后的所有字符. 解决方案:Word窗口下边缘状态栏,找到"改写"按钮,点击,使其切换为"插入",问题解决. 说明:如果找不到"改写"按钮,是因为被隐藏了.右键点击状态栏,可将此按钮调出来.