作为一个屌丝程序员不得不收藏的工具类 一 文件操作类

<pre name="code" class="java">package cn.ipanel.ad.framework.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 * 文件工具类
 * 
 * 
 */
public class FileUtil {
	private static final Logger logger = Logger.getLogger(FileUtil.class);

	private final static int BUFFER = 1024;

	/**
	 * 功 能: 移动文件(只能移动文件) 参 数: strSourceFileName:指定的文件全路径名 strDestDir: 移动到指定的文件夹
	 * 返回值: 如果成功true;否则false
	 * 
	 * @param strSourceFileName
	 * @param strDestDir
	 * @return
	 */
	public static boolean copyTo(String strSourceFileName, String strDestDir) {
		File fileSource = new File(strSourceFileName);
		File fileDest = new File(strDestDir);

		// 如果源文件不存或源文件是文件夹
		if (!fileSource.exists() || !fileSource.isFile()) {
			logger.debug("源文件[" + strSourceFileName + "],不存在或是文件夹!");
			return false;
		}

		// 如果目标文件夹不存在
		if (!fileDest.isDirectory() || !fileDest.exists()) {
			if (!fileDest.mkdirs()) {
				logger.debug("目录文件夹不存,在创建目标文件夹时失败!");
				return false;
			}
		}

		try {
			String strAbsFilename = strDestDir + File.separator
					+ fileSource.getName();

			FileInputStream fileInput = new FileInputStream(strSourceFileName);
			FileOutputStream fileOutput = new FileOutputStream(strAbsFilename);

			logger.debug("开始拷贝文件");

			int count = -1;

			long nWriteSize = 0;
			long nFileSize = fileSource.length();

			byte[] data = new byte[BUFFER];

			while (-1 != (count = fileInput.read(data, 0, BUFFER))) {

				fileOutput.write(data, 0, count);

				nWriteSize += count;

				long size = (nWriteSize * 100) / nFileSize;
				long t = nWriteSize;

				String msg = null;

				if (size <= 100 && size >= 0) {
//					msg = "\r拷贝文件进度:   " + size + "%   \t" + "\t   已拷贝:   " + t;
					//logger.debug(msg);
				} else if (size > 100) {
//					msg = "\r拷贝文件进度:   " + 100 + "%   \t" + "\t   已拷贝:   " + t;
					//logger.debug(msg);
				}

			}

			fileInput.close();
			fileOutput.close();

			logger.debug("拷贝文件成功!");
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static boolean copyTo(String strSourceFileName, String strDestDir,String destName) {
		File fileSource = new File(strSourceFileName);
		File fileDest = new File(strDestDir);

		// 如果源文件不存或源文件是文件夹
		if (!fileSource.exists() || !fileSource.isFile()) {
			logger.debug("源文件[" + strSourceFileName + "],不存在或是文件夹!");
			return false;
		}

		// 如果目标文件夹不存在
		if (!fileDest.isDirectory() || !fileDest.exists()) {
			if (!fileDest.mkdirs()) {
				logger.debug("目录文件夹不存,在创建目标文件夹时失败!");
				return false;
			}
		}

		try {
			String strAbsFilename = strDestDir + File.separator
					+ destName;

			FileInputStream fileInput = new FileInputStream(strSourceFileName);
			FileOutputStream fileOutput = new FileOutputStream(strAbsFilename);

			logger.debug("开始拷贝文件");

			int count = -1;

			long nWriteSize = 0;
			long nFileSize = fileSource.length();

			byte[] data = new byte[BUFFER];

			while (-1 != (count = fileInput.read(data, 0, BUFFER))) {

				fileOutput.write(data, 0, count);

				nWriteSize += count;

				long size = (nWriteSize * 100) / nFileSize;
				long t = nWriteSize;

				String msg = null;

				if (size <= 100 && size >= 0) {
//					msg = "\r拷贝文件进度:   " + size + "%   \t" + "\t   已拷贝:   " + t;
					//logger.debug(msg);
				} else if (size > 100) {
//					msg = "\r拷贝文件进度:   " + 100 + "%   \t" + "\t   已拷贝:   " + t;
					//logger.debug(msg);
				}

			}

			fileInput.close();
			fileOutput.close();

			logger.debug("拷贝文件成功!");
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 功 能: 删除指定的文件 参 数: 指定绝对路径的文件名 strFileName 返回值: 如果删除成功true否则false;
	 * 
	 * @param strFileName
	 * @return
	 */
	public static boolean delete(String strFileName) {
		File fileDelete = new File(strFileName);

		if (!fileDelete.exists() || !fileDelete.isFile()) {
			logger.debug(strFileName + "不存在!");
			return false;
		}

		return fileDelete.delete();
	}

	/**
	 * 功 能: 移动文件(只能移动文件) 参 数: strSourceFileName: 是指定的文件全路径名 strDestDir:
	 * 移动到指定的文件夹中 返回值: 如果成功true; 否则false
	 * 
	 * @param strSourceFileName
	 * @param strDestDir
	 * @return
	 */
	public static boolean moveFile(String strSourceFileName, String strDestDir) {
		if (copyTo(strSourceFileName, strDestDir))
			return delete(strSourceFileName);
		else
			return false;
	}

	/**
	 * 功 能: 创建文件夹 参 数: strDir 要创建的文件夹名称 返回值: 如果成功true;否则false
	 * 
	 * @param strDir
	 * @return
	 */
	public static boolean makeDir(String strDir) {
		File fileNew = new File(strDir);

		if (!fileNew.exists()) {
			return fileNew.mkdirs();
		} else {
			return true;
		}
	}

	/**
	 * 功 能: 删除文件夹 参 数: strDir 要删除的文件夹名称 返回值: 如果成功true;否则false
	 * 
	 * @param strDir
	 * @return
	 */
	public static boolean removeDir(String strDir) {
		File rmDir = new File(strDir);
		if (rmDir.isDirectory() && rmDir.exists()) {
			String[] fileList = rmDir.list();

			for (int i = 0; i < fileList.length; i++) {
				String subFile = strDir + File.separator + fileList[i];
				File tmp = new File(subFile);
				if (tmp.isFile())
					tmp.delete();
				else if (tmp.isDirectory())
					removeDir(subFile);
			}
			rmDir.delete();
		} else {
			return false;
		}
		return true;
	}

	/**
	 * 将byte[]的数据写入文件,如果此文件存在则覆盖掉,如果不存在创建此文件,目录不存在也直接创建其目录。
	 * 
	 * @author lsm
	 * @since
	 * @param filePath 文件全路径.
	 * @param fileData 文件数据.
	 * @return 写文件是否成功.
	 */
	public static boolean directWriteFile(String filePath, byte[] fileData) {
		if (filePath == null || fileData == null) {
			logger.debug("filePath or fileData is null");
			return false;
		} else if (filePath.trim().equals("")) {
			logger.debug("filePath is \"\"!");
			return false;
		}
		String fileDir = filePath.substring(0,
				filePath.lastIndexOf(System.getProperty("file.separator")));
		boolean flag = makeDirectory(fileDir);
		if (!flag) {
			return false;
		}
		FileOutputStream write;
		try {
			write = new FileOutputStream(filePath);
			write.write(fileData);
			write.close();
			logger.debug("write file:" + filePath + " success!");
			return true;
		} catch (FileNotFoundException e) {
			logger.debug(e.getMessage());
		} catch (IOException e) {
			logger.debug(e.getMessage());
		}
		return false;
	}

	/**
	 * 
	 * @author lsm
	 * @since
	 * @param directory 给定的路径表示字符串。
	 * @return 是否成功 成功==true.
	 */
	public static boolean makeDirectory(String directory) {
		File file = new File(directory);
		if (!file.exists()) {
			if (file.mkdirs()) {
				logger.debug("make dirctory success!:" + directory);
				return true;
			} else {
				logger.debug("make dirctory <<<<<<<faile>>>>>>>!:" + directory);
				return false;
			}
		} else {
			logger.debug("this directory is existed!:" + directory);
			return true;
		}
	}

	/**
	 * 将byte[]的数据写入文件,如果此文件存在覆盖掉,如果不存在创建此文件,目录不存在也直接创建其目录.
	 * 
	 * @param filePath 文件全路径.
	 * @param fileData 文件数据.
	 * @return Boolean
	 */
	public static boolean writeFile(String filePath, byte[] fileData) {
		try {
			FileUtils.writeByteArrayToFile(new File(filePath), fileData);
			logger.debug("writeFile the file sucess: " + filePath);
			return true;
		} catch (IOException e) {
			logger.debug("writeFile the file fail: " + filePath);
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 获得所有的文件名.
	 * 
	 * @author lsm
	 */
	public static List<File> getAllFiles(String directoryPath) {
		List<File> allFiles = new ArrayList<File>();
		if (!isHave(directoryPath)) {
			return allFiles;
		} else {
			File file = new File(directoryPath);
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						getAllFiles(files[i].getAbsolutePath());
					} else {
						allFiles.add(files[i]);
					}
				}
				return allFiles;
			} else {
				return allFiles;
			}
		}
	}

	/**
	 * 判断是文件系统中是否存在此文件.
	 * @param filePath 全路径
	 * @return boolean 文件在系统中=true.
	 */
	public static boolean isHave(String filePath) {
		if (filePath == null) {
			logger.debug("not know file isHave .filePath is null! at _File.isHave");
			return true;
		} else if (filePath.trim().equals("")) {
			logger.debug("not know file isHave . filePath is \"\"! at _File.isHave");
			return true;
		}
		File file = new File(filePath);
		if (file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * 将zip解压到指定路径
	 * @author lsm
	 * @since 
	 * @param srcZipFile zip文件
	 * @param destDir 指定路径
	 * @throws IOException
	 */
	public static void unZip(File srcZipFile, String destDir)
			throws IOException {
		unZip(new ZipFile(srcZipFile), destDir);
	}

	/**
	 * 将zip解压到指定路径
	 * @author lsm
	 * @since 
	 * @param srcZipFile zip路径
	 * @param destDir 指定路径
	 * @throws IOException
	 */
	public static void unZip(String srcZipFile, String destDir)
			throws IOException {
		unZip(new ZipFile(srcZipFile), destDir);
	}

	public static void unZip(ZipFile zipFile, String destDir)
			throws IOException {
		Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
		ZipEntry entry = null;
		while (entryEnum.hasMoreElements()) {
			entry = entryEnum.nextElement();
			File destFile = new File(destDir + entry.getName());
			if (entry.isDirectory()) {
				destFile.mkdirs();
			} else {
				destFile.getParentFile().mkdirs();
				InputStream eis = zipFile.getInputStream(entry);
				write(eis, destFile);
			}
		}
	}

	/**
	 * 将输入流中的数据写到指定文件
	 * 
	 * @author lsm
	 * @since
	 * @param inputStream
	 * @param destFile
	 * @throws IOException
	 */
	public static void write(InputStream inputStream, File destFile)
			throws IOException {
		BufferedInputStream bufIs = null;
		BufferedOutputStream bufOs = null;
		try {
			bufIs = new BufferedInputStream(inputStream);
			bufOs = new BufferedOutputStream(new FileOutputStream(destFile));
			byte[] buf = new byte[BUFFER];
			int len = 0;
			while ((len = bufIs.read(buf, 0, buf.length)) > 0) {
				bufOs.write(buf, 0, len);
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			close(bufOs, bufIs);
		}
	}
	
	public static boolean fileIsExists(String filePath){
		File file = new File(filePath);
		return file.exists();
	}

	private static void close(Closeable... streams) {
		try {
			for (Closeable s : streams) {
				if (s != null)
					s.close();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace(System.err);
		}
	}
	
	/**
	 * 递归删除目录里面的所有文件
	 * @author lsm
	 * @param directoryPath	目录路径
	 * @param delDir	是否删除文件夹结构,为false时只删除里面的文件不删除里面的文件夹
	 * @return
	 */
	public static boolean delAllFile(String directoryPath, boolean delDir){
		if (!isHave(directoryPath)) {
			return false;
		} else {
			File file = new File(directoryPath);
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						delAllFile(files[i].getAbsolutePath(),delDir);
						if(delDir)files[i].delete();
					} else {
						files[i].delete();
					}
				}
			} else {
				file.delete();
			}
		}
		return true;
	}
	
	/**
	 * 压缩文件
	 * @author lsm
	 * @param zipfilepath	压缩后文件的绝对路径
	 * @param filedir	需要压缩的文件目录的绝对路径
	 * @param ziprootdir	zip包的根目录,为空字符或者null时表示直接把内容压缩到zip包,不加多一层root目录
	 * @throws IOException
	 */
	public static void zipFile(String zipfilepath, String filedir,
			String ziprootdir) throws IOException {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipfilepath));
		zipFileChild(out, new File(filedir), ziprootdir);
		out.flush();
		out.close();
	}

	/**
	 * 
	 * @author lsm
	 * @param zipOut
	 * @param columFold	
	 * @param file
	 * @throws IOException
	 */
	private static void zipFileChild(ZipOutputStream zipOut, File columFold,
			String file) throws IOException {
		if (columFold.isDirectory()) {
			File[] files = columFold.listFiles();
			if (file == null)
				file = "";
			if (file.length() != 0) {
				file = file + "/";
				zipOut.putNextEntry(new ZipEntry(file));
			}

			for (int i = 0; i < files.length; i++) {
				zipFileChild(zipOut, files[i], file + files[i].getName());
			}
		} else {
			zipOut.putNextEntry(new ZipEntry(file));
			FileInputStream in = new FileInputStream(columFold);
			int len;
			byte[] by = new byte[1024];
			while ((len = in.read(by, 0, 1024)) != -1) {
				zipOut.write(by, 0, len);
			}
			in.close();
		}
	}
	
	/**
	 * 下载文件
	 * @author tianpu
	 * @create 2013-5-10 上午11:20:07
	 * @since 
	 * @param request
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
	public static void download(HttpServletRequest request,  
            HttpServletResponse response, String storeName, String contentType,  
            String realName) throws Exception {  
        response.setContentType("text/html;charset=UTF-8");  
        request.setCharacterEncoding("UTF-8");  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
  
        String ctxPath = request.getSession().getServletContext()  
                .getRealPath("/");  
        String downLoadPath = ctxPath + storeName;  
  
        long fileLength = new File(downLoadPath).length();  
  
        response.setContentType(contentType);  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
        response.setHeader("Content-Length", String.valueOf(fileLength));  
  
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[2048];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }  
        bis.close();  
        bos.close();  
    }  
	
	public static void main(String[] args) {
//		File file = new File("D:/aoc_kfc/pic");
//		File[] files = file.listFiles();
//		for(File f : files){
//			String fileName = f.getName();
//			String fileType = fileName.substring(fileName.indexOf("."));
//			
//			System.out.println(fileName.substring(0,fileName.length()-1));
//		}
		FileUtil.delAllFile("F:/复件 test",false);
	}
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值