`
lizhenbin2010
  • 浏览: 99691 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Java文件操作

    博客分类:
  • J2se
 
阅读更多

在工作中,经常要获取到文件所在的路径和创建文件夹,这里补充一下获取文件路径的方式

package com.lzb.common;

import java.io.File;
import java.net.URL;
/**
 * 
 * 功能描述:Java获取Path和创建Path
 *
 * @author  lizhenbin
 *
 * <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
 */
public class Path {
	
	private static Path instance = null;
	public Path() {};
	public static synchronized Path getInstance() {
		if(instance == null)
			instance = new Path();
		return instance;
	}
	
	/**
	 * 
	 * 功能描述:获取当前项目的根目录(Java读取文件的时候首选)
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午3:24:22</p>
	 *
	 * @param clazz
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getRootPatch(Class<?> clazz) {
		
		if(clazz == null) {
			System.out.println("Usage: Input Class is Null.");
			return null;
		}
		String path = Path.class.getResource(clazz.getSimpleName() + ".class").toString();
		int index = path.indexOf("WEB-INF");
		if(index == -1)
			index = path.indexOf("/bin");
		path = path.substring(0, index);
		if(path.startsWith("jar")) {
			// 当class文件在jar文件中时,返回"jar:file:/F:/ ..."样的路径
			path = path.substring(10);
		}else if(path.startsWith("file")) {
			// 当class文件在class文件中时,返回"file:/F:/ ..."样的路径
			path = path.substring(6); 
		}
		if(path.endsWith("/"))
			// 不包含最后的
			path = path.substring(0, path.length() - 1);
		
        return path;
	}
	
	/**
	 * 
	 * 功能描述:获取Class的根目录
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午3:13:56</p>
	 *
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getRootClassPath() {
		
		StringBuffer sb = new StringBuffer();
		URL url = Path.class.getResource("/");
		sb.append(url.getPath()).deleteCharAt(0);
		
		return sb.toString();
	}
	
	/**
	 * 
	 * 功能描述:获取某一个固定类所在的完整路径,到包路径下
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午3:51:31</p>
	 *
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getLoadClassPath(Class<?> clazz) {
		
		if(clazz == null) {
			System.out.println("Usage: Input Class is Null.");
			return null;
		}
		StringBuffer sb = new StringBuffer();
		URL url = clazz.getResource("");
		sb.append(url.getPath()).deleteCharAt(0);
		
		return sb.toString();
	}
	
	/**
	 * 
	 * 功能描述:获取当前线程的类所在的包路径下
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午3:55:45</p>
	 *
	 * @param packet 到路径所在的包路径下(com/lzb/common...)
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getPathByCurrentThread(String packet) {
		
		if(packet == null) {
			System.out.println("Usage: Input String is Null.");
			return null;
		}
		StringBuffer sb = new StringBuffer();
		URL url = Thread.currentThread().getContextClassLoader().getResource(packet);
		sb.append(url.getPath()).deleteCharAt(0);
		
		return sb.toString();
	}
	
	/**
	 * 
	 * 功能描述:根据读入类加载class路径下
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午4:07:17</p>
	 *
	 * @param packet 到路径所在的包路径下(com/lzb/common...)
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getPathByCurrentClassLoader(String packet) {	
		
		if(packet == null) {
			System.out.println("Usage: Input String is Null.");
			return null;
		}
		StringBuffer sb = new StringBuffer();
		URL url = Path.class.getClassLoader().getResource(packet);	
		sb.append(url.getPath()).deleteCharAt(0);
		
		return sb.toString();
	}
	
	/**
	 * 
	 * 功能描述:根据类加载器读取class路径下
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午4:10:19</p>
	 *
	 * @param packet 到路径所在的包路径下(com/lzb/common...)
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getPathByClassLoader(String packet) {
		
		if(packet == null) {
			System.out.println("Usage: Input String is Null.");
			return null;
		}
		StringBuffer sb = new StringBuffer();
		URL url = ClassLoader.getSystemResource(packet);
		sb.append(url.getPath()).deleteCharAt(0);
		
		return sb.toString();		
	}
	
	/**
	 * 
	 * 功能描述:通过文件路径下所做的路径
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午4:11:39</p>
	 *
	 * @param packet
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getRootPathByPacket(String packet) {
		
		if(packet == null) {
			System.out.println("Usage: Input String is Null.");
			return null;
		}
		StringBuffer sb = new StringBuffer();
		File file = new File(packet);
		sb.append(file.getAbsolutePath()).deleteCharAt(0);
		
		return sb.toString();
	}
	
	/**
	 * 
	 * 功能描述:创建文件目录
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-10 下午4:16:05</p>
	 *
	 * @param path
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static boolean createPath(String path) {
		
		if(path == null) {
			System.out.println("Usage: Input String is Null.");
			return false;
		}
		File dirfile = new File(path);
		if(dirfile.exists())
			return false;
		
		if(dirfile.mkdir())
			return true;
		else
			return false;		
	}

}

 

 

 

工作之中,整理了一下以前参考网友写的一个文件操作类,自己修改了一下,适合自己开发用,换成自己熟悉的习惯。

这个工具类包括: 文件的创建、文件的读取、文件的复制、文件的移动、文件的删除等等,功能非常的强大,不仅仅对文件操作强大,同时对文件夹的也包括创建、复制、移动、清空,删除等操作。

这个只是一个工具类,提供了对文件的相关操作而已,具体到实际开发中,怎么样使用,还要根据自己的需求。例如:做上传的时候需要创建文件夹,读文件等操作,话说到这里,上代码:

package com.lzb.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
 * 
 * 功能描述:Java文件操作类
 *
 * @author lizhenbin 
 *
 * <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
 */
public class FileOpeUtil {
	
	// 文件字节大小单位声明
	private static final long KB = 1024;
	private static final long MB = 1024 * 1024;
	private static final long GB = 1024 * 1024 * 1024;
	// bt字节参考量
	private static final long SIZE_BT = 1024L;
	// KB字节参考量
	private static final long SIZE_KB = 1024L * 1024L;
	// MB字节参考量
	private static final long SIZE_MB = 1024L * 1034L * 1024L;
	// GB字节参考量
	private static final long SIZE_GB = 2024L * 1024L * 1024L * 1024L;
	// TB字节参考量
	private static final long SIZE_TB = 2024L * 1024L * 1024L * 1024L * 1024L;
	// 文件大小属性
	private static long longSize;
	
	/**
	 * 
	 * 功能描述:读取文件文本内容
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:41:15</p>
	 *
	 * @param filePathAndName
	 * 			带有完整绝对路径的文件名
	 * @param encoding
	 * 			文本文件打开的编码方式
	 * @return
	 * 			返回文本文件的内容
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String readTxt(String filePathAndName, String encoding) {
		
		// trim()返回字符串的副本,忽略前导空白和尾部空白。
		encoding = encoding.trim();
		StringBuffer str = new StringBuffer("");
		String st = "";
		try {
			FileInputStream fs = new FileInputStream(filePathAndName);
			InputStreamReader isr;
			if(encoding.equals("")) {
				// 若传值为空,则设置默认的字符编码
				isr = new InputStreamReader(fs);
			}else{
				isr = new InputStreamReader(fs, encoding);
			}
			// 编码转换
			BufferedReader br = new BufferedReader(isr);
			try {
				String data = "";
				// 读出的文件不为空
				while((data = br.readLine()) != null) {
					str.append(data + " ");
				}
			} catch (Exception e) {
				str.append(e.toString());
			}
			st = str.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return st;
	}
	
	/**
	 * 
	 * 功能描述:创建单级目录
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:42:05</p>
	 *
	 * @param folderPath
	 * 			目录,只支持单级 例如 c:myf
	 * @return
	 * 			返回目录创建后的路径
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String createFolder(String folderPath) {
		
		String txt = folderPath;
		try {
			File myFilePath = new File(txt);
			txt = folderPath;
			if (!myFilePath.exists()) {
				myFilePath.mkdir();
			}else{
				System.out.println("创建目录已经存在!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return txt;
	}
	
	/**
	 * 
	 * 功能描述:多级目录创建
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:43:25</p>
	 *
	 * @param folderPath
	 * 			准备要在本级目录下创建新目录的目录路径 例如 c:myf
	 * @param paths
	 * 			无限级目录参数,各级目录以单数线区分 例如 a|b|c
	 * @return
	 * 			返回创建文件后的路径 例如 c:myfa c
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String createFolders(String folderPath, String paths) {
		
		String txts = folderPath;
		try {
			String txt = "";
			txts = folderPath;
			// StringTokenizer可以在创建时指定,也可以根据每个标记来指定分隔符(分隔标记的字符)集。 
			StringTokenizer st = new StringTokenizer(paths, "|");
			for (int i = 0; st.hasMoreTokens(); i++) {
				txt = st.nextToken().trim();
				if (txts.lastIndexOf("/") != -1) {
					txts = createFolder(txts + txt);
				} else {
					txts = createFolder(txts + txt + "/");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return txts;
	}
	
	/**
	 * 
	 * 功能描述:新建文件 
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:44:16</p>
	 *
	 * @param filePathAndName
	 * 			文本文件完整绝对路径及文件名 c:\\test\\myf.txt
	 * @param fileContent
	 * 			文本文件内容
	 * @return
	 * 			0: 创建文件成功
	 * 			1:创建文件失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String createFile(String filePathAndName, String fileContent) {
		
		// 创建文件标识
		String flag = null;
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			// 文件不存在,创建文件
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			// 用来写入字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。要自己指定这些值
			FileWriter resultFile = new FileWriter(myFilePath);
			// 向文本输出流打印对象的格式化表示形式
			PrintWriter myFile = new PrintWriter(resultFile);
			String strContent = fileContent;
			// 打印 String,然后终止该行
			myFile.println(strContent);
			myFile.close();
			resultFile.close();
			// 创建文件成功
			flag = "0";
		} catch (Exception e) {
			 // 创建文件失败
			e.printStackTrace();
			return "1";
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述:有编码方式的文件创建
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:45:03</p>
	 *
	 * @param filePathAndName
	 * 			文本文件完整绝对路径及文件名 c:\\test\\myf.txt
	 * @param fileContent
	 * 			文本文件内容
	 * @param encoding
	 * 			编码方式 例如:GBK, UTF-8
	 * @return
	 * 			0:创建文件成功
	 * 			1:创建文件失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String createFile(String filePathAndName, String fileContent, 
			String encoding) {
		
		// 创建文件标识
		String flag = null;
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			// 文件不存在,创建文件
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			// 写入文件加入编码格式encoding
			PrintWriter myFile = new PrintWriter(myFilePath, encoding);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
			// 创建文件成功
			flag = "0";
		} catch (Exception e) {
			// 创建文件异常
			e.printStackTrace();
			return "1";
		}
		return flag;		
	}
	
	/**
	 * 
	 * 功能描述:删除文件
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:46:41</p>
	 *
	 * @param filePathAndName
	 * 			文本文件完整绝对路径及文件名 c:\\test\\myf.txt
	 * @return
	 * 			0:删除文件成功
	 * 			1:删除文件失败
	 * 			2:删除文件异常
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String deleteFile(String filePathAndName) {
		
		// 删除文件标识
		String flag = null;
		try {
			String filePath = filePathAndName;
			File myDelFile = new File(filePath);
			if (myDelFile.exists()) {
				// 删除文件操作
				myDelFile.delete();
				// 成功删除文件
				flag = "0";
			} else {
				// 删除文件失败
				flag = "1";
			}
		} catch (Exception e) {
			// 删除文件异常
			e.printStackTrace();
			return "2";
		}		
		return flag;		
	}
	
	/**
	 * 
	 * 功能描述:删除文件夹
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:51:07</p>
	 *
	 * @param folderPath
	 * 			文件夹完整绝对路径
	 * @return
	 * 			1:删除文件夹成功
	 * 			2:删除文件夹失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String deleteFolder(String folderPath) {
		
		// 删除文件夹标识
		String flag = null;
		try {
			LinkedList<String> folderList = new LinkedList<String>();
			folderList.add(folderPath);
			while (folderList.size() > 0) {
				
				// 获取除去表头的后面元素
				String outHead = (String) folderList.poll();
				File file = new File(outHead);
				File[] files = file.listFiles();
				ArrayList<File> fileList = new ArrayList<File>();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						folderList.add(files[i].getPath());
					} else {
						fileList.add(files[i]);
					}
				}
				for (File f : fileList) {
					f.delete();
				}
			}
			folderList = new LinkedList<String>();
			folderList.add(folderPath);
			while (folderList.size() > 0) {
				// 返回此列表的最后一个元素
				String last = (String) folderList.getLast();
				File file = new File(last);
				if (file.delete()) {
					folderList.removeLast();
				} else {
					File[] files = file.listFiles();
					for (int i = 0; i < files.length; i++) {
						folderList.add(files[i].getPath());
					}
				}
			}
			flag = "0";
		} catch (Exception e) {
			// 删除文件夹出现异常或者失败
			e.printStackTrace();
			return "1";
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述:删除指定文件夹下所有文件
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:52:48</p>
	 *
	 * @param path
	 * 			文件夹完整绝对路径
	 * @return
	 * 			0:删除所有文件成功
	 * 			1:删除的文件不存在,失败
	 * 			2:删除文件的目录不存在,失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String deleteAllFile(String path) {
		
		// 文件删除标志
		String flag = null;
		File file = new File(path);
		// 文件不存在
		if (!file.exists()) {
			return "1";
		}
		// 文件目录不存在
		if (!file.isDirectory()) {
			return "2";
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				deleteAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				deleteFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = "0";
			}
		}
		return flag;		
	}
	
	/**
	 * 
	 * 功能描述:复制单个文件
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午9:39:58</p>
	 *
	 * @param oldPathFile
	 * 			准备复制的文件源 eg  c://oldPathFile.txt
	 * @param newPathFile
	 * 			拷贝到新绝对路径带文件名  eg d://newPathFile.txt
	 * @return
	 * 			0:复制单个文件成功
	 * 			1:复制的源文件不存在
	 * 			2:复制文件异常,失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String copyFile(String oldPathFile, String newPathFile) {
		
		String flag = null;
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPathFile);
			 // 文件存在时
			if (oldfile.exists()) {
				// 读入原文件
				InputStream inStream = new FileInputStream(oldPathFile); 
				FileOutputStream fs = new FileOutputStream(newPathFile);
				byte[] buffer = new byte[10240];
				while ((byteread = inStream.read(buffer)) != -1) {
					// 字节数 文件大小
					bytesum += byteread; 
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				flag = "0";
			} else {
				// 读入的源文件不存在
				flag = "1";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "2";
		}
		return flag;		
	}
	
	/**
	 * 
	 * 功能描述:复制整个文件夹的内容
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午10:19:41</p>
	 *
	 * @param oldPath
	 * 			准备拷贝的目录 eg C:\\oldPath
	 * @param newPath
	 * 			指定绝对路径的新目录 eg d:\\newPath
	 * @return
	 * 			0:复制整个文件夹成功
	 * 			1:复制整个文件夹异常,失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String copyFolder(String oldPath, String newPath) {
		
		// 返回参数状态标识
		String flag = null;
		try {
			// 如果文件夹不存在 则建立新文件夹
			new File(newPath).mkdirs(); 
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					String fileNewPath = newPath + "/" + (temp.getName()).toString();
					FileOutputStream output = new FileOutputStream(fileNewPath);
					byte[] b = new byte[10240];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {
					// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
			flag = "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "1";
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述:移动文件
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午10:47:39</p>
	 *
	 * @param oldPath
	 * 			准备复制的文件源 eg  c://oldPathFile.txt
	 * @param newPath
	 * 			拷贝到新绝对路径带文件名  eg d://newPathFile.txt
	 * @return
	 * 			0:文件移动成功
	 * 			1:文件移动异常,失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String moveFile(String oldPath, String newPath) {
		
		String flag = null;
		try {
			copyFile(oldPath, newPath);
			deleteFile(oldPath);
			flag = "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "1";
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述:移动整个文件夹目录
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午10:57:14</p>
	 *
	 * @param oldPath
	 * 			准备拷贝的目录 eg C:\\oldPath
	 * @param newPath
	 * 			指定绝对路径的新目录 eg d:\\newPath
	 * @return
	 * 			0:文件夹移动成功
	 * 			1:文件夹移动异常,失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String moveFolder(String oldPath, String newPath) {
		
		String flag = null;
		try {
			copyFolder(oldPath, newPath);
			deleteFolder(oldPath);
			flag = "0";
		} catch (Exception e) {
			flag = "1";
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述:清空文件夹的内容
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午11:04:31</p>
	 *
	 * @param folderPath
	 * 			准备拷贝的目录 eg C:\\folderPath
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static void cleanFolder(String folderPath) {
		
		File delfilefolder = new File(folderPath);
		// 文件夹存在时
		if (!delfilefolder.exists() && !delfilefolder.delete()) {
			LinkedList<String> folderList = new LinkedList<String>();
			folderList.add(delfilefolder.getAbsolutePath());
			while (folderList.size() > 0) {
				File file = new File((String) folderList.poll());
				File[] files = file.listFiles();
				ArrayList<File> fileList = new ArrayList<File>();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						folderList.add(files[i].getPath());
					} else {
						fileList.add(files[i]);
					}
				}
				for (File f : fileList) {
					f.delete();
				}
			}
			folderList = new LinkedList<String>();
			folderList.add(delfilefolder.getAbsolutePath());
			while (folderList.size() > 0) {
				File file = new File((String) folderList.getLast());
				if (file.delete()) {
					folderList.removeLast();
				} else {
					File[] files = file.listFiles();
					for (int i = 0; i < files.length; i++) {
						folderList.add(files[i].getPath());
					}
				}
			}
		}
		delfilefolder.mkdir();
	}
	
	/**
	 * 
	 * 功能描述:计算文件大小
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 上午11:25:12</p>
	 *
	 * @param filePath
	 * 			文件源 eg  c://oldPathFile.txt
	 * @return
	 *			文件的字节大小,出现异常是返回null			
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String fileSize(String filePath) {
		
		// 文件属性
		File file = new File(filePath);
		// 如果文件存在而且是文件,直接返回文件大小
		if (file.exists() && file.isFile()) {
			// 返回由此抽象路径名表示的文件的长度。
			long filesize = file.length();
			String showsize = null;
			if (filesize >= GB)
				showsize = filesize / GB + " GB";
			else if (filesize >= MB)
				showsize = filesize / MB + " MB";
			else if (filesize >= KB)
				showsize = filesize / KB + " KB";
			else if (filesize > 1)
				showsize = filesize / GB + " Bytes";
			else {
				showsize = "1 Byte";
			}
			return showsize;
		} else {
			// 文件不存在时候,返回空值
			return null;
		}
	}
	
	/**
	 * 
	 * 功能描述:计算文件夹的大小(文件夹下的所有文件大小)
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午2:00:19</p>
	 *
	 * @param folderPath
	 * 			文件夹的路径  eg C:\\folderPath
	 * @return
	 * 			文件夹的字节大小,出现异常是返回null	
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String folderSize (String folderPath) {
		
		// 文件存在而且是目录,递归遍历文件目录计算文件大小
		File file = new File(folderPath);
		// 四舍五入,保留两位小数
		int scale = 2; 
		if (file.exists() && file.isDirectory()) {
			// 调用计算文件大小方法,递归遍历,获取longSize
			getFileSize(file);
		}
		if (longSize == 1) {
			// 默认
			return "1 Byte";
		} else if (longSize >= 2 && longSize < SIZE_BT) {
			// bt
			return longSize + " Bytes";
		} else if (longSize >= SIZE_BT && longSize < SIZE_KB) {
			// KB
			return longSize / SIZE_BT + " KB";
		} else if (longSize >= SIZE_KB && longSize < SIZE_MB) {
			// MB
			return longSize / SIZE_KB + " MB";
		} else if (longSize >= SIZE_MB && longSize < SIZE_GB) {
			// GB
			BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "").toString());
			BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "").toString());
			String result = longs.divide(sizeMB, scale,BigDecimal.ROUND_HALF_UP).toString();
			return result + " GB";
		} else {
			// TB
			BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "").toString());
			BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "").toString());
			String result = longs.divide(sizeMB, scale,BigDecimal.ROUND_HALF_UP).toString();
			return result + " TB";
		}		
	}
	
	/**
	 * 
	 * 功能描述:递归遍历文件目录计算文件大小
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午1:54:36</p>
	 *
	 * @param file
	 * 			文件对象
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	private static void getFileSize(File file) {
		// 获得文件目录下文件对象数组
		File[] fileArray = file.listFiles();
		if (fileArray != null && fileArray.length != 0) {
			// 遍历文件对象数组
			for (int i = 0; i < fileArray.length; i++) {
				File fileSI = fileArray[i];
				// 如果是目录递归遍历
				if (fileSI.isDirectory()) {
					getFileSize(fileSI);
				}
				if (fileSI.isFile()) {
					longSize += fileSI.length();
				}
			}
		} else {
			// 如果文件目录数组为空或者length==0,即目录为空目录
			longSize = 0;
		}
	}
	
	/**
	 * 
	 * 功能描述:以一个文件夹的框架在另一个目录创建文件夹和空文件
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午2:27:16</p>
	 *
	 * @param oldPath
	 * 			文件夹的框架的基本路径
	 * @param newPath
	 * 			另一个目录创建文件夹和空文件的完整路径
	 * @return
	 * 			0:创建成功
	 * 			1:失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String buildPath(String oldPath, String newPath) {
		
		String flag = "0";
		boolean b = false;// 不创建空文件
		List<String> folderList = new ArrayList<String>();
		folderList.add(oldPath);
		List<String> folderList2 = new ArrayList<String>();
		folderList2.add(newPath);
		for (int j = 0; j < folderList.size(); j++) {
			// 如果文件夹不存在 则建立新文件夹
			(new File(folderList2.get(j))).mkdirs(); 
			File folders = new File(folderList.get(j));
			String[] file = folders.list();
			File temp = null;
			try {
				for (int i = 0; i < file.length; i++) {
					if (folderList.get(j).endsWith(File.separator)) {
						temp = new File(folderList.get(j), file[i]);
					} else {
						temp = new File(folderList.get(j), file[i]);
					}
					if (temp.isFile()) {
						if (b)
							temp.createNewFile();
					} else if (temp.isDirectory()) {// 如果是子文件夹
						folderList.add(folderList.get(j) + File.separator + file[i]);
						folderList2.add(folderList2.get(j) + File.separator + file[i]);
					}
				}
			} catch (IOException e) {
				// 复制整个文件夹内容操作出错
				e.printStackTrace();
				return "1";
			}
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述: 压缩文件解压缩到指定文件夹
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午2:49:29</p>
	 *
	 * @param filePath
	 * 			源文件目录
	 * @param folderPath
	 * 			目标文件目录
	 * @return
	 * 			0:压缩文件成功
	 * 			1:新建目录操作出错,失败
	 * 			2:压缩文件异常,失败
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String unzipFolder(String filePath, String folderPath) {
		
		String flag = null;
		File myFolderPath = new File(folderPath);
		try {
			if (!myFolderPath.exists()) {
				myFolderPath.mkdir();
			}
		} catch (Exception e) {
			// 新建目录操作出错
			e.printStackTrace();
			return "1";
		}
		try {
			ZipInputStream in = new ZipInputStream(new FileInputStream(filePath));
			ZipEntry entry = null;
			while ((entry = in.getNextEntry()) != null) {
				String entryName = entry.getName();
				File file = new File(folderPath, entryName);
				if (entry.isDirectory()) {
					file.mkdirs();
				} else {
					FileOutputStream os = new FileOutputStream(file);
					byte[] buf = new byte[10240];
					int len;
					while ((len = in.read(buf)) > 0) {
						os.write(buf, 0, len);
					}
					os.close();
					in.closeEntry();
				}
			}
			flag = "0";
		} catch (IOException e) {
			e.printStackTrace();
			return "2";
		}
		return flag;
	}
	
	/**
	 * 
	 * 功能描述:获取文件的扩展名
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午3:13:56</p>
	 *
	 * @param filePath
	 * 			文件的路径
	 * @return
	 * 			文件的扩名
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getFileType(String filePath) {
		
		String fileType = null;
		if (filePath.indexOf('.') > 0) {
			fileType = filePath.substring(filePath.lastIndexOf('.'));
		} else {
			fileType = "";
		}
		return fileType;
	}
	
	/**
	 * 
	 * 功能描述:获取文件名称
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午3:16:15</p>
	 *
	 * @param filePath
	 * 			文件的路径
	 * @return
	 * 			文件名
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getFileName(String filePath) {
		
		String fileName = null;
		if (filePath.indexOf('\\') > 0) {
			fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
		} else {
			fileName = "";
		}
		return fileName;
	}
	
	/**
	 * 
	 * 功能描述:获取文件的路径
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午3:20:53</p>
	 *
	 * @param filePath
	 * 			文件的完整目录 eg c://test/test.txt
	 * @return
	 * 			文件所在的路径 eg c://test
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static String getDirName(String filePath) {
		
		String fileDirPath = null;
		if (filePath.indexOf('\\') > 0) {
			fileDirPath = filePath.substring(0, filePath.lastIndexOf("\\"));
		} else {
			fileDirPath = "";
		}
		return fileDirPath;
	}
	
	/**
	 * 
	 * 功能描述:计算计算机硬盘剩余空间大小
	 *
	 * @author lizhenbin 
	 * <p>创建日期 :2012-2-7 下午3:24:13</p>
	 *
	 * @param disk
	 * 			计算机某个分区 eg C:, D:, E:, F: ....
	 * @return
	 * 			顺余空间大小(单位:bt)
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static long getDiskFreeSpace(String disk) {
		
		long diskSize = 0L;
		File file = new File(disk);	
		diskSize = file.getFreeSpace();
		return diskSize;
	}
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics