File Util 类

package com.nexaweb.vbtoxal.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import info.monitorenter.cpdetector.io.*;

import org.apache.log4j.Logger;

/**
 * File utils. Read, write, copy files, search file recursively and so on.
 * 
 * @author zyao
 * 
 */
public class FileManager {
	private Logger log = Logger.getLogger(FileManager.class);
	ArrayList<File> flisList = new ArrayList<File>();
	// Create the proxy:
	CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance(); // A
																			// singleton.

	/**
	 * 删除文件,可以是单个文件或文件夹
	 * 
	 * @param fileName
	 *            待删除的文件名
	 * @return 文件删除成功返回true,否则返回false
	 */
	public static boolean delete(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			System.out.println("删除文件失败:" + fileName + "文件不存在");
			return false;
		} else {
			if (file.isFile()) {

				return deleteFile(fileName);
			} else {
				return deleteDirectory(fileName);
			}
		}
	}

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

	/**
	 * 删除目录(文件夹)以及目录下的文件
	 * 
	 * @param dir
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符结尾,自动添加文件分隔符
		if (!dir.endsWith(File.separator)) {
			dir = dir + File.separator;
		}
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			System.out.println("删除目录失败" + dir + "目录不存在!");
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
			// 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			System.out.println("删除目录失败");
			return false;
		}

		// 删除当前目录
		if (dirFile.delete()) {
			System.out.println("删除目录" + dir + "成功!");
			return true;
		} else {
			System.out.println("删除目录" + dir + "失败!");
			return false;
		}
	}

	public List<File> getFileListByExtension(String fileDir, String extension)
			throws Exception {

		// Make sure the directory exists
		File dir = new File(fileDir);
		if (!dir.exists()) {
			throw new Exception("Invalid Dir " + fileDir);
		}

		// Use FileFilter to get only extension files
		FileFilter filter = new FileExtensionFileFilter("." + extension);

		File[] currenFiles = dir.listFiles(filter);
		for (int j = 0; j < currenFiles.length; j++) {
			File f = currenFiles[j];
			if (f.isFile()) {
				flisList.add(f);
			}
		}

		File[] files = dir.listFiles();

		// Iterate through the files found
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (!file.isFile()) {
				getFileListByExtension(file.getAbsolutePath(), extension);
			}
		}

		return flisList;
	}

	public FileManager() {
		// Add the implementations of
		// info.monitorenter.cpdetector.io.ICodepageDetector:
		// This one is quick if we deal with unicode codepages:
		detector.add(new ByteOrderMarkDetector());
		// This one does the tricks of exclusion and frequency detection, if
		// first implementation is
		// unsuccessful:
		detector.add(JChardetFacade.getInstance()); // Another singleton.
		detector.add(ASCIIDetector.getInstance()); // Fallback, see javadoc.
		// UnicodeDetector
		detector.add(UnicodeDetector.getInstance());

	}

	public String readFile(File file) {
		StringBuffer sb = new StringBuffer();
		try {
			// BufferedReader br = new BufferedReader(new FileReader(file));
			// new InputStreamReader(new FileInputStream(fileName),"UTF-8")
			// fix garbled
			// BufferedReader br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(file),"UTF-8"));
			java.nio.charset.Charset charset = null;
			charset = detector.detectCodepage(file.toURL());

			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), charset));
			String lineText = br.readLine();

			while (lineText != null) {
				sb = sb.append(lineText + "\n");
				lineText = br.readLine();
			}

		} catch (Exception e) {

		}
		return sb.toString();
	}

	public void copyAllFilesByExtension(String sourceDir, String targetDir,
			String extension) throws Exception {
		String keep = sourceDir;
		copyAllFilesByExtension(keep, sourceDir, targetDir, extension);
	}

	public void copyAllFilesByExtension(String keep, String sourceDir,
			String targetDir, String extension) throws Exception {
		// Make sure the directory exists
		File dir = new File(sourceDir);
		if (!dir.exists()) {
			throw new Exception("Invalid Dir " + sourceDir);
		}

		// Use FileFilter to get only extension files
		FileFilter filter = new FileExtensionFileFilter("." + extension);

		File[] currenFiles = dir.listFiles(filter);
		for (int j = 0; j < currenFiles.length; j++) {
			File f = currenFiles[j];
			File aFile = f.getAbsoluteFile();
			// CopyFile(f.getAbsolutePath(),
			// targetDir+File.separator+aFile.getName());
			String su = f.getAbsolutePath();
			String au = su.substring(keep.length());
			CopyFile(f.getAbsolutePath(), targetDir + File.separator + au);
		}

		File[] files = dir.listFiles();

		// Iterate through the files found
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (!file.isFile()) {
				copyAllFilesByExtension(keep, file.getAbsolutePath(),
						targetDir, extension);
			}
		}
	}

	public void CopyFile(String source, String taget) {
		try {
			FileInputStream input = new FileInputStream(source);
			File dir = new File(taget.substring(0, taget
					.lastIndexOf(File.separator)));
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileOutputStream output = new FileOutputStream(taget);

			// int in = input.read();
			// while (in != -1) {
			// output.write(in);
			// in = input.read();
			// }
			int bytesRead;
			byte[] buf = new byte[4 * 1024]; // 4K buffer
			while ((bytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, bytesRead);
			}
			output.flush();
			output.close();
			input.close();
		} catch (IOException e) {
			System.out.println(e.toString());
		}

	}

	public static void main(String[] args) {
		// Make sure the directory exists
		String dirName = "D:\\VB\\ICU\\source";
		FileManager fm = new FileManager();
		try {
			// fm.listFile(dirName);
			List<File> fl = fm.getFileListByExtension(dirName, "frm");
			fm.readFile(fl.get(0));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 

你可能感兴趣的:(File)