文件操作---java.io.File

主要的文件操作包:

【rt.jar】文件基本操作需要的包

【ant-1.9.3.jar】zip操作用到的包

 

上载 文件/文件夹

File srcFile = newFile("D:\\11\\22.txt");

File directory = newFile("D:\\11\\22");

 

注意分割符,不能是下面这样:

FilesrcFile = new File("D:\11\22.txt");

 

一、基本操作

 

1、判断文件是否存在

boolean isExist = srcFile.exists();

 

2、判断是不是文件

boolean isFile =srcFile.isFile();

 

3、判断是不是文件夹

boolean isDirectory= directory.isDirectory();

 

4、删除文件或文件夹

booleanresult=srcFile.delete();

如果srcFile是文件夹,那么必须保证其没有子文件夹,否则删不掉。

 

5、获取文件/文件夹的路径

String dirPath =dirFile.getPath();

打印出来为是【D:\11

 

6、获取文件的绝对路径

String absolutePath= srcFile.getAbsolutePath();

打印出来是【D:\11\22.txt

 

7、获取文件所在的上一级文件夹

File dirFile =srcFile.getParentFile();

 

8获取文件夹下的所有文件和子目录

File[] files =directory.listFiles();

 

9、获取文件分隔符常量

String separator =File.separator;

打印出来为是【\

 

10、创建文件夹【22】,前提是目录【D:\\11】必须存在

directory.mkdir();

 

11、创建一个文件

boolean result =srcFile.createNewFile();

 

二、文件复制

把文件22.txt复制一份,复制后的文件为77.txt

// 复制文件
	public static void main(String[] args) throws IOException {
		File srcFile = new File("D:\\11\\22.txt");
		File newFile = new File("D:\\11\\77.txt");
		
		// 读取的位数
		int readByte = 0;
		InputStream ins = null;
		OutputStream outs = null;
		try {
			// 打开源文件的输入流
			ins = new FileInputStream(srcFile);
			// 打开目标文件的输出流
			outs = new FileOutputStream(newFile);
			
			//每次读取的字节数
			byte[] buf = new byte[1024];
			
			// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕
			while ((readByte = ins.read(buf)) != -1) {
				// 将读取的字节流写入到输出流
				outs.write(buf, 0, readByte);
			}
		} catch (Exception e) {
			log.info("复制文件失败:" + e.getMessage());
		} finally {
			// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
			if (outs != null) {
				try {
					outs.close();
				} catch (IOException oute) {
					oute.printStackTrace();
				}
			}
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException ine) {
					ine.printStackTrace();
				}
			}
		}
	}


 三、将文件压缩成zip包

 将目录【D:\\11】下的文件【test.txt】压缩成zip包【D:\\11\\test.zip】。

	/**
	 * 获取待压缩文件在ZIP文件中entry的名字,即相对于根目录的相对路径名
	 * @param dirPat 目录路径
	 * @param file 目录路径下的文件或文件夹
	 * @return
	 */
	private static String getEntryName(String dirPath, File file) {
		String dirPaths = dirPath;
		if (!dirPaths.endsWith(File.separator)) {
			dirPaths = dirPaths + File.separator;
		}
		String filePath = file.getAbsolutePath();
		// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
		if (file.isDirectory()) {
			filePath += "/";
		}
		int index = filePath.indexOf(dirPaths);

		return filePath.substring(index + dirPaths.length());
	}
	
	// 将文件压缩成zip包
	public static void main(String[] args) throws IOException {
		
		//目录
		File fileDir = new File("D:\\11");
		//目录下待压缩的文件
		File file = new File(fileDir, "test.txt");
		
		//设置压缩后的zip包
		File descFile = new File("D:\\11\\test.zip");
		
		//判断目录是否存在
		if (!fileDir.exists() || !fileDir.isDirectory()) {
			log.warn("文件压缩失败,目录[D:\\11]不存在!");
			return;
		}
		//获取目录的路径
		String dirPath = fileDir.getAbsolutePath();
		
		try {
			//创建zip输出流
			ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
			
			FileInputStream fin = null;
			ZipEntry entry = null;
			
			// 创建复制缓冲区
			byte[] buf = new byte[4096];
			int readByte = 0;
			if (file.isFile()) {
				try {
					// 创建一个文件输入流
					fin = new FileInputStream(file);
					
					//获取相对于压缩包根目录的相对路径名,如果entryName="hh\\test.txt",那么压缩包的根路径下会有一个hh文件夹,文件夹里面有个test.txt文件
					String entryName = getEntryName(dirPath, file);
					
					// 创建一个ZipEntry
					entry = new ZipEntry(entryName);
					// 存储信息到压缩文件
					zouts.putNextEntry(entry);
					// 复制字节到压缩文件
					while ((readByte = fin.read(buf)) != -1) {
						zouts.write(buf, 0, readByte);
					}
					zouts.closeEntry();
					fin.close();
					System.out.println("添加文件" + file.getAbsolutePath() + "到zip文件中!");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			zouts.close();
		} catch (Exception e) {
			log.warn("文件压缩失败:" + e.getMessage());
			e.printStackTrace();
		}
	}

四、解压ZIP包

将压缩包22.zip解压在D:\11文件夹下。

	/**
	 * 解压缩ZIP文件,将ZIP文件里的内容解压到descFileName目录下
	 * 
	 * @param zipFileName  需要解压的ZIP文件,比如:D:\\11\\22.zip
	 * @param descFileName 解压后的存放路径,比如:D:\\11
	 */
	public static boolean unZipFiles(String zipFileName, String descFileName) {
		String descFileNames = descFileName;
		if (!descFileNames.endsWith(File.separator)) {
			descFileNames = descFileNames + File.separator;
		}
		try {
			// 根据ZIP文件创建ZipFile对象
			ZipFile zipFile = new ZipFile(zipFileName);
			ZipEntry entry = null;
			String entryName = null;
			String descFileDir = null;
			byte[] buf = new byte[4096];
			int readByte = 0;
			// 获取ZIP文件里所有的entry
			@SuppressWarnings("rawtypes")
			Enumeration enums = zipFile.getEntries();
			// 遍历所有entry
			while (enums.hasMoreElements()) {
				entry = (ZipEntry) enums.nextElement();
				// 获得entry的名字
				entryName = entry.getName();
				descFileDir = descFileNames + entryName;
				if (entry.isDirectory()) {
					// 如果entry是一个目录,则创建目录
					new File(descFileDir).mkdirs();
					continue;
				} else {
					// 如果entry是一个文件,则创建父目录
					new File(descFileDir).getParentFile().mkdirs();
				}
				File file = new File(descFileDir);
				// 打开文件输出流
				OutputStream os = new FileOutputStream(file);
				// 从ZipFile对象中打开entry的输入流
				InputStream is = zipFile.getInputStream(entry);
				while ((readByte = is.read(buf)) != -1) {
					os.write(buf, 0, readByte);
				}
				os.close();
				is.close();
			}
			zipFile.close();
			log.info("文件解压成功!");
			return true;
		} catch (Exception e) {
			log.warn("文件解压失败:" + e.getMessage());
			return false;
		}
	}

五、删除文件或文件夹

	/**
	 * 
	 * 删除目录及目录下的文件
	 * 
	 * @param dirName 被删除的目录所在的文件路径 比如:dirName=“D:\svn\部署脚本\test” 或者  dirName=“D:\svn\部署脚本\test\” 那么将删除test这个文件夹
	 * @return 如果目录删除成功,则返回true,否则返回false
	 */
	public static boolean deleteDirectory(String dirName) {
		String dirNames = dirName;
		if (!dirNames.endsWith(File.separator)) {
			dirNames = dirNames + File.separator;
		}
		File dirFile = new File(dirNames);
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			log.info(dirNames + "目录不存在!");
			return true;
		}
		boolean flag = true;
		// 列出全部文件及子目录
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = FileUtils.deleteFile(files[i].getAbsolutePath());
				// 如果删除文件失败,则退出循环
				if (!flag) {
					break;
				}
			}
			// 删除子目录
			else if (files[i].isDirectory()) {
				flag = FileUtils.deleteDirectory(files[i].getAbsolutePath());
				// 如果删除子目录失败,则退出循环
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			log.info("删除目录失败!");
			return false;
		}
		// 删除当前目录
		if (dirFile.delete()) {
			log.info("删除目录" + dirName + "成功!");
			return true;
		} else {
			log.info("删除目录" + dirName + "失败!");
			return false;
		}

	}

六、文件操作工具类

package com.openeap.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件操作工具类 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能
 * 
 * @author lcw
 * @version 2013-01-15
 */
public class FileUtils {

	private static Logger log = LoggerFactory.getLogger(FileUtils.class);

	/**
	 * 复制单个文件,如果目标文件存在,则不覆盖
	 * 
	 * @param srcFileName
	 *            待复制的文件名
	 * @param descFileName
	 *            目标文件名
	 * @return 如果复制成功,则返回true,否则返回false
	 */
	public static boolean copyFile(String srcFileName, String descFileName) {
		return FileUtils.copyFileCover(srcFileName, descFileName, false);
	}

	/**
	 * 复制单个文件
	 * 
	 * @param srcFileName
	 *            待复制的文件名
	 * @param descFileName
	 *            目标文件名
	 * @param coverlay
	 *            如果目标文件已存在,是否覆盖
	 * @return 如果复制成功,则返回true,否则返回false
	 */
	public static boolean moveFile(String srcFileName, String descFileName, boolean coverlay) {
		if (copyFileCover(srcFileName, descFileName, coverlay)) {
			// 删除文件
			if (delFile(srcFileName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 复制单个文件
	 * 
	 * @param srcFileName
	 *            待复制的文件名
	 * @param descFileName
	 *            目标文件名
	 * @param coverlay
	 *            如果目标文件已存在,是否覆盖
	 * @return 如果复制成功,则返回true,否则返回false
	 */
	public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {
		descFileName = descFileName.replace(" ", "");
		File srcFile = new File(srcFileName);
		// 判断源文件是否存在
		if (!srcFile.exists()) {
			log.info("复制文件失败,源文件" + srcFileName + "不存在!");
			return false;
		}
		// 判断源文件是否是合法的文件
		else if (!srcFile.isFile()) {
			log.info("复制文件失败," + srcFileName + "不是一个文件!");
			return false;
		}
		File descFile = new File(descFileName);
		// 判断目标文件是否存在
		if (descFile.exists()) {
			// 如果目标文件存在,并且允许覆盖
			if (coverlay) {
				log.info("目标文件已存在,准备删除!");
				if (!FileUtils.delFile(descFileName)) {
					log.info("删除目标文件" + descFileName + "失败!");
					return false;
				}
			} else {
				log.info("复制文件失败,目标文件" + descFileName + "已存在!");
				return false;
			}
		} else {
			if (!descFile.getParentFile().exists()) {
				// 如果目标文件所在的目录不存在,则创建目录 
				log.info("原文件名:" + srcFileName + "||目标文件名:" + descFileName);
				log.info("目标文件所在的目录不存在,创建目录!");
				// 创建目标文件所在的目录 
				if (!descFile.getParentFile().mkdirs()) {
					log.info("原文件名:" + srcFileName + "||目标文件名:" + descFileName);
					log.info("创建目标文件所在的目录失败!");
					return false;
				}
			}
		}

		// 准备复制文件
		// 读取的位数
		int readByte = 0;
		InputStream ins = null;
		OutputStream outs = null;
		try {
			// 打开源文件
			ins = new FileInputStream(srcFile);
			// 打开目标文件的输出流
			outs = new FileOutputStream(descFile);
			byte[] buf = new byte[1024];
			// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕
			while ((readByte = ins.read(buf)) != -1) {
				// 将读取的字节流写入到输出流
				outs.write(buf, 0, readByte);
			}
			log.info("复制单个文件" + srcFileName + "到" + descFileName + "成功!");
			return true;
		} catch (Exception e) {
			log.info("复制文件失败:" + e.getMessage());
			return false;
		} finally {
			// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
			if (outs != null) {
				try {
					outs.close();
				} catch (IOException oute) {
					oute.printStackTrace();
				}
			}
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException ine) {
					ine.printStackTrace();
				}
			}
		}
	}

	/**
	 * 复制整个目录的内容,如果目标目录存在,则不覆盖
	 * 
	 * @param srcDirName
	 *            源目录名
	 * @param descDirName
	 *            目标目录名
	 * @return 如果复制成功返回true,否则返回false
	 */
	public static boolean copyDirectory(String srcDirName, String descDirName) {
		return FileUtils.copyDirectoryCover(srcDirName, descDirName, false);
	}

	/**
	 * 复制整个目录的内容
	 * 
	 * @param srcDirName   源目录名
	 * @param descDirName   目标目录名
	 * @param coverlay 如果目标目录存在,是否覆盖
	 * @return 如果复制成功返回true,否则返回false
	 */
	public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {
		descDirName = descDirName.replaceAll(" ", "");
		File srcDir = new File(srcDirName);
		// 判断源目录是否存在
		if (!srcDir.exists()) {
			log.info("复制目录失败,源目录" + srcDirName + "不存在!");
			return false;
		}
		// 判断源目录是否是目录
		else if (!srcDir.isDirectory()) {
			log.info("复制目录失败," + srcDirName + "不是一个目录!");
			return false;
		}
		// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
		String descDirNames = descDirName;
		if (!descDirNames.endsWith(File.separator)) {
			descDirNames = descDirNames + File.separator;
		}
		File descDir = new File(descDirNames);
		// 如果目标文件夹存在
		if (descDir.exists()) {
			if (coverlay) {
				// 允许覆盖目标目录
				log.info("目标目录已存在,准备删除!");
				if (!FileUtils.delFile(descDirNames)) {
					log.info("删除目录" + descDirNames + "失败!");
					return false;
				}
			} else {
				log.info("目标目录复制失败,目标目录" + descDirNames + "已存在!");
				return false;
			}
		} else {
			// 创建目标目录 
			if (!descDir.mkdirs()) {
				log.info("创建目标目录[" + descDir + "]失败!");
				return false;
			}

		}

		boolean flag = true;
		// 列出源目录下的所有文件名和子目录名
		File[] files = srcDir.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 如果是一个单个文件,则直接复制
			if (files[i].isFile()) {
				flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName());
				// 如果拷贝文件失败,则退出循环
				if (!flag) {
					break;
				}
			}
			// 如果是子目录,则继续复制目录
			if (files[i].isDirectory()) {
				flag = FileUtils.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName());
				// 如果拷贝目录失败,则退出循环
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			log.info("复制目录" + srcDirName + "到" + descDirName + "失败!");
			return false;
		}
		log.info("复制目录" + srcDirName + "到" + descDirName + "成功!");
		return true;

	}

	/**
	 * 
	 * 删除文件,可以删除单个文件或文件夹
	 * 
	 * @param fileName  被删除的文件名
	 * @return 如果删除成功,则返回true,否是返回false
	 */
	public static boolean delFile(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			log.info(fileName + "文件不存在!");
			return true;
		} else {
			if (file.isFile()) {
				return FileUtils.deleteFile(fileName);
			} else {
				return FileUtils.deleteDirectory(fileName);
			}
		}
	}

	/**
	 * 
	 * 删除单个文件
	 * 
	 * @param fileName  被删除的文件名
	 * @return 如果删除成功,则返回true,否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				log.info("删除单个文件" + fileName + "成功!");
				return true;
			} else {
				log.info("删除单个文件" + fileName + "失败!");
				return false;
			}
		} else {
			log.info(fileName + "文件不存在!");
			return true;
		}
	}

	/**
	 * 
	 * 删除目录及目录下的文件
	 * 
	 * @param dirName 被删除的目录所在的文件路径 比如:dirName=“D:\svn\部署脚本\test” 或者  dirName=“D:\svn\部署脚本\test\” 那么将删除test这个文件夹
	 * @return 如果目录删除成功,则返回true,否则返回false
	 */
	public static boolean deleteDirectory(String dirName) {
		String dirNames = dirName;
		if (!dirNames.endsWith(File.separator)) {
			dirNames = dirNames + File.separator;
		}
		File dirFile = new File(dirNames);
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			log.info(dirNames + "目录不存在!");
			return true;
		}
		boolean flag = true;
		// 列出全部文件及子目录
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = FileUtils.deleteFile(files[i].getAbsolutePath());
				// 如果删除文件失败,则退出循环
				if (!flag) {
					break;
				}
			}
			// 删除子目录
			else if (files[i].isDirectory()) {
				flag = FileUtils.deleteDirectory(files[i].getAbsolutePath());
				// 如果删除子目录失败,则退出循环
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			log.info("删除目录失败!");
			return false;
		}
		// 删除当前目录
		if (dirFile.delete()) {
			log.info("删除目录" + dirName + "成功!");
			return true;
		} else {
			log.info("删除目录" + dirName + "失败!");
			return false;
		}

	}

	/**
	 * 创建单个文件
	 * 
	 * @param descFileName  文件名,包含路径
	 * @return 如果创建成功,则返回true,否则返回false
	 */
	public static boolean createFile(String descFileName) {
		File file = new File(descFileName);
		if (file.exists()) {
			log.info("文件" + descFileName + "已存在!");
			return false;
		}
		if (descFileName.endsWith(File.separator)) {
			log.info(descFileName + "为目录,不能创建目录!");
			return false;
		}
		if (!file.getParentFile().exists()) {
			// 如果文件所在的目录不存在,则创建目录
			if (!file.getParentFile().mkdirs()) {
				log.warn("创建文件所在的目录失败!");
				return false;
			}
		}

		// 创建文件
		try {
			if (file.createNewFile()) {
				log.info(descFileName + "文件创建成功!");
				return true;
			} else {
				log.warn(descFileName + "文件创建失败!");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.warn(descFileName + "文件创建失败!");
			return false;
		}

	}

	/**
	 * 创建目录
	 * 
	 * @param descDirName
	 *            目录名,包含路径
	 * @return 如果创建成功,则返回true,否则返回false
	 */
	public static boolean createDirectory(String descDirName) {
		String descDirNames = descDirName;
		if (!descDirNames.endsWith(File.separator)) {
			descDirNames = descDirNames + File.separator;
		}
		File descDir = new File(descDirNames);
		if (descDir.exists()) {
			log.info("目录" + descDirNames + "已存在!");
			return false;
		}
		// 创建目录
		if (descDir.mkdirs()) {
			log.info("目录" + descDirNames + "创建成功!");
			return true;
		} else {
			log.warn("目录" + descDirNames + "创建失败!");
			return false;
		}

	}

	/**
	 * 压缩文件或目录
	 * 
	 * @param srcDirName
	 *            压缩的根目录
	 * @param fileName
	 *            根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
	 * @param descFileName
	 *            目标zip文件
	 */
	public static void zipFiles(String srcDirName, String fileName, String descFileName) {
		// 判断目录是否存在
		if (srcDirName == null) {
			log.warn("文件压缩失败,目录" + srcDirName + "不存在!");
			return;
		}
		File fileDir = new File(srcDirName);
		if (!fileDir.exists() || !fileDir.isDirectory()) {
			log.warn("文件压缩失败,目录" + srcDirName + "不存在!");
			return;
		}
		String dirPath = fileDir.getAbsolutePath();
		File descFile = new File(descFileName);
		try {
			ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
			if ("*".equals(fileName) || "".equals(fileName)) {
				FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
			} else {
				File file = new File(fileDir, fileName);
				if (file.isFile()) {
					FileUtils.zipFilesToZipFile(dirPath, file, zouts);
				} else {
					FileUtils.zipDirectoryToZipFile(dirPath, file, zouts);
				}
			}
			zouts.close();
			log.info(descFileName + "文件压缩成功!");
		} catch (Exception e) {
			log.warn("文件压缩失败:" + e.getMessage());
			e.printStackTrace();
		}

	}

	/**
	 * 解压缩ZIP文件,将ZIP文件里的内容解压到descFileName目录下
	 * 
	 * @param zipFileName  需要解压的ZIP文件,比如:D:\\11\\22.zip
	 * @param descFileName 解压后的存放路径,比如:D:\\11
	 */
	public static boolean unZipFiles(String zipFileName, String descFileName) {
		String descFileNames = descFileName;
		if (!descFileNames.endsWith(File.separator)) {
			descFileNames = descFileNames + File.separator;
		}
		try {
			// 根据ZIP文件创建ZipFile对象
			ZipFile zipFile = new ZipFile(zipFileName);
			ZipEntry entry = null;
			String entryName = null;
			String descFileDir = null;
			byte[] buf = new byte[4096];
			int readByte = 0;
			// 获取ZIP文件里所有的entry
			@SuppressWarnings("rawtypes")
			Enumeration enums = zipFile.getEntries();
			// 遍历所有entry
			while (enums.hasMoreElements()) {
				entry = (ZipEntry) enums.nextElement();
				// 获得entry的名字
				entryName = entry.getName();
				descFileDir = descFileNames + entryName;
				if (entry.isDirectory()) {
					// 如果entry是一个目录,则创建目录
					new File(descFileDir).mkdirs();
					continue;
				} else {
					// 如果entry是一个文件,则创建父目录
					new File(descFileDir).getParentFile().mkdirs();
				}
				File file = new File(descFileDir);
				// 打开文件输出流
				OutputStream os = new FileOutputStream(file);
				// 从ZipFile对象中打开entry的输入流
				InputStream is = zipFile.getInputStream(entry);
				while ((readByte = is.read(buf)) != -1) {
					os.write(buf, 0, readByte);
				}
				os.close();
				is.close();
			}
			zipFile.close();
			log.info("文件解压成功!");
			return true;
		} catch (Exception e) {
			log.warn("文件解压失败:" + e.getMessage());
			return false;
		}
	}

	/**
	 * 将目录压缩到ZIP输出流
	 * 
	 * @param dirPath
	 *            目录路径
	 * @param fileDir
	 *            文件信息
	 * @param zouts
	 *            输出流
	 */
	public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
		if (fileDir.isDirectory()) {
			File[] files = fileDir.listFiles();
			// 空的文件夹
			if (files.length == 0) {
				// 目录信息
				ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
				try {
					zouts.putNextEntry(entry);
					zouts.closeEntry();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}

			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					// 如果是文件,则调用文件压缩方法
					FileUtils.zipFilesToZipFile(dirPath, files[i], zouts);
				} else {
					// 如果是目录,则递归调用
					FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts);
				}
			}

		}

	}

	/**
	 * 将文件压缩到ZIP输出流
	 * 
	 * @param dirPath
	 *            目录路径
	 * @param file
	 *            文件
	 * @param zouts
	 *            输出流
	 */
	public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
		FileInputStream fin = null;
		ZipEntry entry = null;
		// 创建复制缓冲区
		byte[] buf = new byte[4096];
		int readByte = 0;
		if (file.isFile()) {
			try {
				// 创建一个文件输入流
				fin = new FileInputStream(file);
				// 创建一个ZipEntry
				entry = new ZipEntry(getEntryName(dirPath, file));
				// 存储信息到压缩文件
				zouts.putNextEntry(entry);
				// 复制字节到压缩文件
				while ((readByte = fin.read(buf)) != -1) {
					zouts.write(buf, 0, readByte);
				}
				zouts.closeEntry();
				fin.close();
				System.out.println("添加文件" + file.getAbsolutePath() + "到zip文件中!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 获取待压缩文件在ZIP文件中entry的名字,即相对于根目录的相对路径名
	 * @param dirPat 目录路径
	 * @param file 目录路径下的文件或文件夹
	 * @return
	 */
	private static String getEntryName(String dirPath, File file) {
		String dirPaths = dirPath;
		if (!dirPaths.endsWith(File.separator)) {
			dirPaths = dirPaths + File.separator;
		}
		String filePath = file.getAbsolutePath();
		// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
		if (file.isDirectory()) {
			filePath += "/";
		}
		int index = filePath.indexOf(dirPaths);

		return filePath.substring(index + dirPaths.length());
	}

	/***
	 * 获取指定目录下的所有的文件(不包括文件夹),采用了递归
	 * 
	 * @author cyp
	 * @param obj
	 *            path file
	 * @return
	 */
	public static ArrayList<File> getListFiles(Object obj) {
		File directory = null;
		if (obj instanceof File) {
			directory = (File) obj;
		} else {
			directory = new File(obj.toString());
		}
		ArrayList<File> files = new ArrayList<File>();
		if (directory.isFile()) {
			files.add(directory);
			return files;
		} else if (directory.isDirectory()) {
			File[] fileArr = directory.listFiles();
			for (int i = 0; i < fileArr.length; i++) {
				File fileOne = fileArr[i];
				files.addAll(getListFiles(fileOne));
			}
		}
		return files;
	} 
	/**
	 * 
	 * @desc 格式化文件大小单位
	 * @param size
	 * @return 文件大小 ,两位小数点 (带单位B,K,M,G)
	 * @author liwp
	 * @date  2014年10月13日 下午5:31:46
	 */
	public static String FormetFileSize(long size) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (size < 1024) {
			fileSizeString = df.format((double) size) + "B";
		} else if (size < 1048576) {
			fileSizeString = df.format((double) size / 1024) + "K";
		} else if (size < 1073741824) {
			fileSizeString = df.format((double) size / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) size / 1073741824) + "G";
		}
		return fileSizeString;
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值