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();
} } } }
file相关的操作,(md5,word转html,复制,删除等)的更多相关文章
- C#操作Office.word(二)
在上一篇文章"C#操作Office.word(一)"中我们讲述了如何使用VS2010引用COM中Miscrosoft Word 14.0 Object Library实现创建文档, ...
- R语言文件相关的操作
1. 文件系统介绍 R语言对文件系统的操作,包括文件操作和目录操作,函数API都定义在base包中. 2. 目录操作 2.1 查看目录 查看当前目录下的子目录. # 启动R程序 ~ R # 当前的目录 ...
- linux下关于压缩、解压相关的操作
本文转自: http://alex09.iteye.com/blog/647128 很不错的linux下关于压缩.解压相关的操作,适合于linux初学者. .tar 解包:tar xvf Fil ...
- Java操作Microsoft Word之jacob
转自: 现在我们一起来看看,用Java如何操作Microsoft Word. jacob,官网是http://danadler.com/jacob 这是一个开源的工具.最新版本1.7 官方 ...
- 封装Email相关的操作
package com.opslab.util; import javax.activation.DataHandler;import javax.activation.DataSource;impo ...
- JAVASE02-Unit06: 文件操作——File 、 文件操作—— RandomAccessFile
Unit06: 文件操作--File . 文件操作-- RandomAccessFile java.io.FileFile的每一个实例是用来表示文件系统中的一个文件或目录 package day06; ...
- 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期
[源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...
- 关于C#和ASP.NET中对App.config和Web.config文件里的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作
最近我做的一些项目,经常需要用到对应用程序的配置文件操作,如app.config和web.config的配置文件,特别是对配置文件中的[appSettings]和[connectionStrings] ...
- C++ STL中Map的相关排序操作:按Key排序和按Value排序 - 编程小径 - 博客频道 - CSDN.NET
C++ STL中Map的相关排序操作:按Key排序和按Value排序 - 编程小径 - 博客频道 - CSDN.NET C++ STL中Map的相关排序操作:按Key排序和按Value排序 分类: C ...
随机推荐
- Kafka的架构设计(目前翻译最好的一稿)
转自:http://www.oschina.net/translate/kafka-design 参与翻译(4人):fbm, 飞翔的猴子, Khiyuan, nesteaa 感谢这些同志们的辛勤工作, ...
- 30分钟LINQ教程【转】
千万别被这个页面的滚动条吓到!!! 我相信你一定能在30分钟之内看完它!!! 在说LINQ之前必须先说说几个重要的C#语言特性 一:与LINQ有关的语言特性 1.隐式类型 (1)源起 在隐式类型出现之 ...
- 更改Mysql数据库存储位置
默认安装位置 C:\Program Files\MySQL\MySQL Server 5.7 一.首先把mysql的服务先停掉. 二.更改MySQL配置文件My.ini中的数据库存储主路径 打开MyS ...
- C#秘密武器之多线程——参数与返回值
线程函数要么没有参数,要么只能有一个object参数,而且均没有返回值,这样就大大降低了程序的灵活性,其实我们想要的是能像普通方法一样正常使用参数和返回值!能不能实现这个需求呢?下面就介绍两种方法 一 ...
- Java中Object转化为int类型
转自:http://blog.sina.com.cn/s/blog_5f8421fb010162kb.html Java中由Object类型转化为int类型时,不能直接转化,先是将Object类型转化 ...
- 广告系统的smart pricing是什么
smart pricing这个词来源于google的Adwords系统,指的是系统能够根据流量质量对流量方的收入进行打折,为的是让广告主获得更高的ROI(投资回报率).将smart pricing的使 ...
- 事件轮询 event loop
Understanding the node.js event loop The first basic thesis of node.js is that I/O is expensive: So ...
- C++ opencv高速样例学习——读图显示
1.关键函数 1. 读入图片 imread(图片或位置,显示格式)默觉得:IMREAD_COLOR 显示格式: IMREAD_UNCHANGED =-1 // 8bit, color or no ...
- hdu2647(拓扑排序)
链接:点击打开链接 题意:每一个人的基本工资为888,给出两个人的关系a,b,代表a的工资比b高问满足全部条件的话,最少须要支付多少钱 代码: #include <map> #includ ...
- poj 2391 Ombrophobic Bovines, 最大流, 拆点, 二分, dinic, isap
poj 2391 Ombrophobic Bovines, 最大流, 拆点, 二分 dinic /* * Author: yew1eb * Created Time: 2014年10月31日 星期五 ...