Java文件操作类封装(一)

2014-11-24 08:39:13 · 作者: · 浏览: 0
java文件操作类,简单封装,封装了复制,剪切,删除目录,压缩解压zip,等常用功能
package com.wiker;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.BufferedReader;  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileFilter;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.PrintWriter;  
import java.math.BigInteger;  
import java.nio.ByteBuffer;  
import java.nio.MappedByteBuffer;  
import java.nio.channels.FileChannel;  
import java.security.MessageDigest;  
import java.text.DecimalFormat;  
import java.util.Arrays;  
import java.util.HashSet;  
import java.util.List;  
import java.util.Set;  
import java.util.zip.ZipEntry;  
import java.util.zip.ZipInputStream;  
import java.util.zip.ZipOutputStream;  
  
  
/** 
 * @author Wiker Yong Email:wikeryong@gmail.com 
 * @date 2013-11-8 下午6:21:45 
 * @version 1.0-SNAPSHOT 
 */  
@SuppressWarnings("resource")  
public class FileUtils {  
      
    /** 
     * 获取文件MD5值 
     *  
     * @param file 
     * @return 
     */  
    public static String getMd5ByFile(File file) {  
        String value = null;  
        FileInputStream in = null;  
        try {  
            in = new FileInputStream(file);  
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0,  
                    file.length());  
            MessageDigest md5 = MessageDigest.getInstance("MD5");  
            md5.update(byteBuffer);  
            BigInteger bi = new BigInteger(1, md5.digest());  
            value = bi.toString(16);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != in) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return value;  
    }  
      
    /** 
     * 获取文件大小 
     *  
     * @param file 
     * @return 
     */  
    public static long getFileLength(File file)  
            throws IOException {  
        FileInputStream fis = null;  
        fis = new FileInputStream(file);  
        return fis.available();  
    }  
      
    /** 
     * 读取文件到二进制 
     *  
     * @author WikerYong Email:yw_312@foxmail.com 
     * @version 2012-3-23 上午11:47:06 
     * @param file 
     * @return 
     * @throws IOException 
     */  
    public static byte[] getBytesFromFile(File file)  
            throws IOException {  
        InputStream is = new FileInputStream(file);  
          
        long length = file.length();  
          
        if (length > Integer.MAX_VALUE) {  
            // File is too large  
        }  
          
        byte[] bytes = new byte[(int) length];  
          
        // Read in the bytes  
        int offset = 0;  
        int numRead = 0;  
        while (offset < bytes.length  
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {  
            offset += numRead;  
        }  
          
        // Ensure all the bytes have been read in  
        if (offset < bytes.length) {  
            throw new IOException("不能读取文件: " + file.getName());  
        }  
          
        is.close();  
        return bytes;  
    }  
      
    /** 
     * 获取标准文件大小,如30KB,15.5MB 
     *  
     * @param file 
     * @return 
     * @throws IOException 
     */  
    public static String getFileSize(File file)  
            throws IOException {  
        long size = getFileLength(file);  
        DecimalFormat df = new DecimalFormat("###.##");  
        float f;  
        if (size < 1024 * 1024) {  
            f = (float) ((float) size / (float) 1024);  
            return (df.format(new Float(f).doubleva lue()) + " KB");  
        } else {  
            f = (float) ((float) size / (float) (1024 * 1024));  
            return (df.format(new Float(f).doubleva lue()) + " MB");  
        }  
          
    }  
      
    /** 
     * 复制文件 
     *  
     * @param f1 
     *            源文件 
     * @param f2 
     *            目标文件 
     * @throws Exception 
     */  
    public static void copyFile(File f1, File f2)  
            throws Exception {  
        int length = 2097152;  
        FileInputStream in = new FileInputStream(f1);  
        FileOutputStream out = new FileOutputStream(f2);  
        FileChannel inC = in.getChannel();  
        FileChannel outC = out.getChannel();  
        ByteBuffer b = null;  
        while (true) {  
            if (inC.position() == inC.size()) {  
                inC.close();  
                outC.close();  
            }  
            if ((inC.size() - inC.position()) < length) {  
                length = (int) (inC.size() - inC.position());  
            } else  
                length = 2097152;  
            b = ByteBuffer.allocateDirect(length);  
            inC.read(b);  
            b.flip();  
            outC.write(b);  
            outC.force(false);  
        }  
    }  
      
    /** 
     * 检查文件是否存在 
     *  
     * @param fileName 
     * @return 
     * @throws IOException 
     */  
    public static boolean existFile(String fileName)  
            throws IOException {  
        File file = new File(fileName);  
        if (!file.exists()) {  
            throw new IOException("文件未找到:" + fileName);  
        }  
        return file.exists();  
    }  
      
    /** 
     * 删除文件 
     *  
     * @param fileName 
     */  
    public static void deleteFile(String fileName)  
            throws IOException {  
        File file = new File(fileName);  
        if (!file.exists()) {  
            throw new IOException("文件未找到:" + fileName);  
        }  
        file.delete();  
    }  
      
    /** 
     * 读取文件到字符串 
     *  
     * @param fileName 
     * @return 
     * @throws IOException 
     */  
    public static String readFile(String fileName)  
            throws IOException {  
        File file = new File(fileName);  
        if (!file.exists()) {  
            throw new IOException("文件未找到:" + fileName);  
        }  
          
        BufferedReader in = new BufferedReader(new FileReader(file));  
        StringBuffer sb = new StringBuffer();  
        String str = "";  
        while ((str = in.readLine()) != null) {  
            sb.append(str);  
        }  
        in.close();  
        return sb.toString();  
    }  
      
    /** 
     * 获取目录所有所有文件和文件夹 
     *  
     * @param fileName 
     * @return 
     * @throws IOException 
     */  
    public static List
listFiles(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { throw new IOException("文件未找到:" + fileName); } return Arrays.asList(file.listFiles()); } /** * 创建目录 * * @param dir */ public static void mkdir(String dir) { String dirTemp = dir; File dirPath = new File(dirTemp); if (!dirPath.exists()) { dirPath.mkdir(); } } /** * 新建文件 * * @param fileName * String 包含路径的文件名 如:E:\phsftp\src\123.txt * @param content * String 文件内容 */ public static void createNewFile(String fileName, String content) throws IOException { String fileNameTemp = fileName; File filePath = new File(fileNameTemp); if (!filePath.exists()) { filePath.createNewFile(); } FileWriter fw = new FileWriter(filePath); PrintWrite