当前位置:编程学习 > JAVA >>

我们爱分享---一个文件工具类

发现爱分享活动大家的热度在降低,再分享一个支持一下。


最近陆陆续续的在做一些和文件相关的工作,今天无事就整理了一些近来整理的处理文件的工具类,有原创也有从网上拿来直接用的,拿来分享,以后继续完善。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 操作文件工具类
 * 
 * @author Administrator 2011-8-5 下午03:40:00
 * 
 * 
 */
public class FileUtil {

static final int BUFFER = 1024;

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

/**
 * 获取文件夹中文件的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 指定的文件
 * @param str 加上的字符串
 * @return 返回文件重名名后的文件名
 */
public static String reNameAddStr(File file, String str) {
String fileName = file.getName();

// 获得去掉后缀名后的文件名
String name = fileName.substring(0, fileName.lastIndexOf("."));

// 获得文件的后缀名
String extendName = fileName.substring(fileName.lastIndexOf("."),
fileName.length());

String destName = name + str + extendName;

file.renameTo(new File(file.getParent() + "\\" + destName));
return destName;
}

/**
 * 从指定文件的文件名中去掉指定字符串
 * @param file 指定文件
 * @param str 去掉的字符串
 * @return 返回文件的重命名后的文件名
 */
public static String reNameDelStr(File file, String str) {

String fileName = file.getName();

if(fileName == null || str == null || fileName.length() <= str.length()) {
return "";
}

// 获得去掉后缀名后的文件名
String name = fileName.substring(0, fileName.lastIndexOf("."));

//获得去掉str后的文件名
String realName = name.substring(0,name.length()-str.length());

// 获得文件的后缀名
String extendName = fileName.substring(fileName.lastIndexOf("."),
fileName.length());

String destName = realName + extendName;

file.renameTo(new File(file.getParent() + "\\" + destName));
return destName;
}

/**
 * 把文件重命名,文件名后加上1970年距今的毫秒数,防止文件重名
 * 
 * @param fileName
 * @return
 */
public static String reNameAddTime(String fileName) {

// 获得去掉后缀名后的文件名
String name = fileName.substring(0, fileName.lastIndexOf("."));

// 获得文件的后缀名
String extendName = fileName.substring(fileName.lastIndexOf("."),
fileName.length());
return name + new Date().getTime() + extendName;
}

/**
 * 把文件重命名,文件名为1970年距今的毫秒数,防止文件重名
 * 
 * @param fileName
 * @return
 */
public static String reNameToTime(String fileName) {

// 获得文件的后缀名
String extendName = fileName.substring(fileName.lastIndexOf("."),
fileName.length());
return new Date().getTime() + extendName;
}

/**
 * 把文件名进行还原,去掉后面的时间,时间百年内仍是13位
 * 
 * @param fileName
 * @return
 */
public static String reNameDelTime(String fileName) {

// 获得去掉后缀名后的文件名
String name = fileName.substring(0, fileName.lastIndexOf("."));

// 获得文件的后缀名
String extendName = fileName.substring(fileName.lastIndexOf("."),
fileName.length());

return name.substring(0, name.length() - 13) + extendName;
}

/**
 * 用zip格式压缩文件
 * 
 * @param zipFile
 *            压缩后的文件名 包含路径 如:"c:\\test.zip"
 * @param inputFile
 *            要压缩的文件 可以是文件或文件夹 如:"c:\\test" 或 "c:\\test.doc"
 * @throws Exception
 * 
 *             ant下的zip工具默认压缩编码为UTF-8编码,而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
 * 
 *             用ant压缩后放到windows上面会出现中文文件名乱码,用winRAR压缩的文件,用ant解压也会出现乱码,
 * 
 *             所以,在用ant处理winRAR压缩的文件时,要设置压缩编码
 */
public static void zip(File zipFile, String inputFile) throws Exception {
File f = new File(inputFile);
// File temp = new File(zipFileName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

// 设置压缩编码
out.setEncoding("GBK");// 设置为GBK后在windows下就不会乱码了,如果要放到Linux或者Unix下就不要设置了
zip(out, f, "");// 递归压缩方法
System.out.println("zip done");
out.close();
}

private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
System.out.println("Zipping   " + f.getName()); // 记录日志,开始压缩
if (f.isDirectory()) { // 如果是文件夹,则获取下面的所有文件
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));// 此处要将文件写到文件夹中只用在文件名前加"/"再加文件夹名
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else { // 如果是文件,则压缩
out.putNextEntry(new ZipEntry(base)); // 生成下一个压缩节点
FileInputStream in = new FileInputStream(f); // 读取文件内容
int len;
byte[] buf = new byte[BUFFER];
while ((len = in.read(buf, 0, BUFFER)) != -1) {
out.write(buf, 0, len); // 写入到压缩包
}
in.close();
}
}

/**
 * 解压缩zip文件
 * 
 * @param fileName
 *            要解压的文件名 包含路径 如:"c:\\test.zip"
 * @param filePath
 *            解压后存放文件的路径 如:"c:\\temp"
 * @throws Exception
 */
public static void unZip(String fileName, String filePath) throws Exception {
ZipFile zipFile = new ZipFile(fileName, "GBK"); // 以“GBK”编码创建zip文件,用来处理winRAR压缩的文件。
Enumeration emu = zipFile.getEntries();

while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
if (entry.isDirectory()) {
new File(filePath + entry.getName()).mkdirs();
continue;
}
BufferedInputStream bis = new BufferedInputStream(zipFile
.getInputStream(entry));

File file = new File(filePath + entry.getName());
File parent = file.getParentFile();
if (parent != null && (!parent.exists())) {
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

byte[] buf = new byte[BUFFER];
int len = 0;
while ((len = bis.read(buf, 0, BUFFER)) != -1) {
fos.write(buf, 0, len);
}
bos.flush();
bos.close();
bis.close();
System.out.println("解压文件:" + file.getName());
}
zipFile.close();
}

public static void main(String[] args) throws Exception {
//unZip("D:\\test\\新建文件夹.zip", "D:\\test\\");
// zip(new File("D:\\test\\新建文件夹.zip"), "D:\\test\\新建文件夹");
System.out.println(getFileMD5(new File("D:\\test\\新建文件夹.zip")));
System.out.println(getFileMD5(new File("D:\\test\\1.zip")));
File file = new File("D:\\test\\test2cf4bb1ab1c4c64c4a504306f9b08556.zip");
System.out.println(reNameDelStr(file, getFileMD5(file)));
}

}




顺便问一下,推荐的贴子也可以结贴吧? --------------------编程问答-------------------- 学习了,谢谢楼主分享哈 --------------------编程问答-------------------- 呵呵,感谢分享哟。 --------------------编程问答-------------------- 谢谢分享~~~ --------------------编程问答-------------------- 不错哦!牛哥,学习了 --------------------编程问答-------------------- 不错  ,学习了 --------------------编程问答-------------------- 恩 这种分享 我喜欢~~ --------------------编程问答-------------------- 看看先 --------------------编程问答-------------------- 谢谢楼主! --------------------编程问答-------------------- 我试了下上面的压缩和解压的代码
想到官网上下载最新的包,找半天没找到,后来终于找了一个官网上有个commons-compress-1.2-bin.zip,发现挺像的,就下下来看看,发现里面包的结构变化很大,类名很像,但也有变化,就改了下代码,发现可以了,经测试,灰常好用,现把修改过的代码贴上

传送门:commons-compress-1.2-bin.zip

需要引入的包
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;


public static void zip(File zipFile, String inputFile) throws Exception {
        File f = new File(inputFile);
        // File temp = new File(zipFileName);
        ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(zipFile));

        // 设置压缩编码
        out.setEncoding("GBK");// 设置为GBK后在windows下就不会乱码了,如果要放到Linux或者Unix下就不要设置了
        zip(out, f, f.getName());// 递归压缩方法,调用下面的方法
        System.out.println("zip done");
//out.finish();
        out.close();
    }

    private static void zip(ZipArchiveOutputStream out, File f, String base)
            throws Exception {
        System.out.println("Zipping   " + f.getName()); // 记录日志,开始压缩
        if (f.isDirectory()) { // 如果是文件夹,则获取下面的所有文件
            File[] fl = f.listFiles();
            out.putArchiveEntry(new ZipArchiveEntry(base + "/"));// 此处要将文件写到文件夹中只用在文件名前加"/"再加文件夹名
            //base = base.length() == 0 ? "" : base + "/";
base = base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else { // 如果是文件,则压缩
            out.putArchiveEntry(new ZipArchiveEntry(base)); // 表示zip文件里的压缩文件的名称,后面由"/",表示这是一个文件夹
            FileInputStream in = new FileInputStream(f); // 读取文件内容
            int len;
            byte[] buf = new byte[BUFFER];
            while ((len = in.read(buf, 0, BUFFER)) != -1) {
                out.write(buf, 0, len); // 写入到压缩包
            }
out.flush();
out.closeArchiveEntry();// 注意要关闭这一句
            in.close();
        }

    }

    public static void unZip(String fileName, String filePath) throws Exception {
        ZipFile zipFile = new ZipFile(fileName, "GBK"); // 以“GBK”编码创建zip文件,用来处理winRAR压缩的文件。
        Enumeration emu = zipFile.getEntries();

        while (emu.hasMoreElements()) {
            ZipArchiveEntry entry = (ZipArchiveEntry) emu.nextElement();
// 如果是文件夹
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
//创建此抽象路径名指定的目录,包括所有必需但不存在的父目录
                continue;
            }

//如果是文件
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

            File file = new File(filePath + entry.getName());
//System.out.println(entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
// 也是为了缓冲
            //BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            byte[] buf = new byte[BUFFER];
            int len = 0;
            while ((len = bis.read(buf, 0, BUFFER)) != -1) {
                fos.write(buf, 0, len);
            }
            //bos.flush();
            //bos.close(
fos.close();
            bis.close();
            System.out.println("解压文件:" + entry.getName());
        }
        zipFile.close();
    }

    public static void main(String[] args) throws Exception {
        
        //zip(new File("f:/pic.zip"), "f:/pic.jpg");
//zip(new File("f:/z.zip"), "g:/z");

unZip("E:\\[edubt]uTorrent.zip", "f:/test/");

        //System.out.println(getFileMD5(new File("f:/1.jpg")));
        //System.out.println(getFileMD5(new File("D:\\test\\1.zip")));
    }
--------------------编程问答-------------------- 这个压缩解压很实用啊,还没弄过,有时间看看,嘿嘿 --------------------编程问答--------------------
引用 9 楼 dxqrr 的回复:
我试了下上面的压缩和解压的代码
想到官网上下载最新的包,找半天没找到,后来终于找了一个官网上有个commons-compress-1.2-bin.zip,发现挺像的,就下下来看看,发现里面包的结构变化很大,类名很像,但也有变化,就改了下代码,发现可以了,经测试,灰常好用,现把修改过的代码贴上

传送门:commons-compress-1.2-bin.zip

需要引入的包
impo……

用的包是ant的包。。。。这样中文不会乱码 --------------------编程问答-------------------- 顺便推荐个网站 http://www.findjar.com/index.x  能根据类来搜索响应的jar包
补充:Java ,  Java EE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,