⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileutil.java

📁 文件基本类源代码
💻 JAVA
字号:


import java.io.*;
import java.util.*;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtil {

	/**
	 * 获得日志类以便控制日志输出
	 */
	private static final Log log = LogFactory.getLog(FileUtil.class);

	/**
	 * 获取系统属性,存储在哈希表中
	 */
	public final static Hashtable SYS_HT = System.getProperties();

	/**
	 * 获取系统默认文件编码
	 */
	public final static String FILE_ENCODEING = (SYS_HT.get("file.encoding") == null || ""
			.equals(SYS_HT.get("file.encoding"))) ? "GBK" : (String) SYS_HT
			.get("file.encoding");

	/**
	 * 获取系统文件分隔符
	 */
	public final static String FILE_SEPARATOR = (String) (SYS_HT.get("file.separator"));

	/**
	 * 获取系统行分隔符
	 */
	public final static String LINE_SEPARATOR = (String) (SYS_HT.get("line.separator"));

	/**
	 * 转换本地编码至Ascii码
	 * 
	 * @param options
	 *            附加参数
	 * @param inputfile
	 *            要转换编码的文件
	 * @param outputfile
	 *            输出文件
	 * @throws IOException
	 */
	public static void native2Ascii(String options, String inputfile,
			String outputfile) throws IOException {
		String command = "native2ascii " + options + " " + inputfile + " "
				+ outputfile;
		// native2ascii -encoding gbk wap.txt wap.properties
		BaseUtil.runCommand(command);
	}

	/**
	 * 转换本地编码至Ascii码
	 * 
	 * @param inputfile
	 *            要转换编码的文件
	 * @param outputfile
	 *            输出文件
	 * @throws IOException
	 */

	public static void native2Ascii(String inputfile, String outputfile)
			throws IOException {
		String options = "-encoding " + FILE_ENCODEING;
		native2Ascii(options, inputfile, outputfile);
	}

	/**
	 * 返回指定文件的编码
	 * 
	 * @param fileName
	 *            文件名
	 * @return 检测到的编码
	 */

	public static String getCharset(String fileName) {
		FileInputStream fis = null;
		// System.out.println("现在的文件是:" + fileName);
		try {
			fis = new FileInputStream(fileName);
			return getChartset(fis);
			/*
			 * byte[] c = new byte[3]; int i=0; try {
			 * if((i=fis.read(c))==-1)return "GBK"; } catch (IOException e) {
			 * e.printStackTrace(); } for (byte j:c)System.out.print(j+" ");
			 */
			/*
			 * if(c[0]==-17 && c[1]==-69 && c[2]==-65) { return "UTF8"; }
			 * if(c[0]==13 && c[1]==10) { return "UTF8"; } return "GBK";
			 */
			/*
			 * if(c[0]>=-17) { if(c[0]==-17 && c[1]==-69 && c[2]==-65) { return
			 * "UTF8"; } else if(c[0]==-2 && c[1]==-1) { return "UTF-16BE"; }
			 * else if(c[0]==-1 && c[1]==-2) { return "Unicode"; } else { return
			 * "GBK"; } } else { return "GBK"; }
			 */
		} catch (FileNotFoundException e) {
			// e.printStackTrace();
			log.error("错误:文件未找到!", e);
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				// e.printStackTrace();
				log.error("错误:文件输入流关闭失败!", e);
			}
		}
		return FILE_ENCODEING;

	}

	/**
	 * 返回指定输入流的编码
	 * 
	 * @param in
	 *            输入流
	 * @return 检测到的编码
	 */

	private static String getChartset(InputStream in) {

		String charset = new org.picksun.io.CharsetDetector(in).getCharset();
		if (charset == null || "".equals(charset)
				|| "ASCII".equalsIgnoreCase(charset)) {
			charset = FILE_ENCODEING;
		}
		return charset;
	}

	/**
	 * 拷贝文件到指定文件,如果指定文件不存在,自动生成文件; 如果指定文件存在,则自动覆盖该文件. 该方法能自动捕获异常并输出(使用log4j)
	 * 
	 * @param srcFileName
	 *            源文件
	 * @param tagFileName
	 *            目标文件(指定文件)
	 */

	public static void copyFile(String srcFileName, String tagFileName) {
		/*
		 * FileInputStream in=new FileInputStream(src); File file=new
		 * File(dest); if(!file.exists()) file.createNewFile(); FileOutputStream
		 * out=new FileOutputStream(file); int c; byte buffer[]=new byte[1024];
		 * while((c=in.read(buffer))!=-1){ for(int i=0;i<c;i++)
		 * out.write(buffer[i]); } in.close(); out.close();
		 */
		File in = new File(srcFileName);
		File out = new File(tagFileName);
		FileInputStream inputStream = null;
		FileChannel inChannel = null;
		MappedByteBuffer inBuffer = null;
		long inputSize = 0;
		FileChannel outChannel = null;
		FileOutputStream outputStream = null;
		try {
			if (!out.exists())
				try {
					out.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					log.error("错误:文件" + tagFileName + "创建失败!", e);
				}

			inputStream = new FileInputStream(in);
			inChannel = inputStream.getChannel();
			inputSize = inChannel.size();
			inBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0,
					inputSize);

			// 使用通道方式复制文件
			outputStream = new FileOutputStream(out);
			outChannel = outputStream.getChannel();
			outChannel.write(inBuffer);
			// 关闭相关对象
		} catch (FileNotFoundException e) {
			// e.printStackTrace();
			log.error("错误:文件" + srcFileName + "未找到!", e);
		} catch (IOException e2) {
			// e2.printStackTrace();
			log.error("错误:文件操作出错!", e2);
		} finally {
			try {
				inChannel.close();
				inputStream.close();
				outChannel.close();
				outputStream.close();
			} catch (IOException e) {
				log.error("错误:文件流关闭失败!", e);
				// e.printStackTrace();
			}
		}

	}

	/**
	 * 拷贝文件路径到指定路径,如果指定路径或文件不存在,自动生成路径或文件. 该方法能自动捕获异常并输出(使用log4j)
	 * 
	 * @param srcPath
	 *            源路径
	 * @param tagPath
	 *            目标路径(指定路径)
	 */

	public static void copyDir(String srcPath, String tagPath) {
		File dir = new File(srcPath);
		new File(tagPath).mkdir();
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					copyDir(srcPath + FILE_SEPARATOR + tmp[i].getName(),
							tagPath + FILE_SEPARATOR + tmp[i].getName());
				} else {
					copyFile(tmp[i].toString(), tagPath + FILE_SEPARATOR
							+ tmp[i].getName());
				}
			}
		}
	}

	/**
	 * 删除文件路径. 该方法会自动从子路径开始, 先删除文件, 再删除文件夹
	 * 
	 * @param path
	 */

	public static void delDir(String path) {
		File dir = new File(path);
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					delDir(path + FILE_SEPARATOR + tmp[i].getName());
				} else {
					tmp[i].delete();
				}
			}
			dir.delete();
		}
	}

	/**
	 * 显示指定路径下所有文件的编码信息
	 * 
	 * @param path
	 *            指定路径
	 */

	public static void detailDir(String path) {
		File dir = new File(path);
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					detailDir(path + FILE_SEPARATOR + tmp[i].getName());
				} else {
					System.out.println(tmp[i].getPath() + "的字符编码为:"
							+ getCharset(tmp[i].getPath()));
					/*
					 * log.info(tmp[i].getPath() + "的字符编码为:" +
					 * getCharset(tmp[i].getPath()));
					 */
				}
			}
		}
	}

	/**
	 * 读取文件,用指定字符串替换掉文件的字符串. 该方法能自动捕获异常并输出(使用log4j). 该方法能够自动识别文件编码
	 * 
	 * @param file
	 *            文件
	 * @param fromString
	 *            要被替换的字符串
	 * @param toString
	 *            用来替换的字符串
	 */
	public static void replaceFile(String file, String[] fromString,
			String[] toString) {
		String charset = FileUtil.getCharset(file);
		replaceFile(file, charset, fromString, toString);
	}

	/**
	 * 读取文件,用指定字符串替换掉文件的字符串. 该方法能自动捕获异常并输出(使用log4j). 该方法能够自动识别文件编码
	 * 
	 * @param file
	 *            文件
	 * @param fromString
	 *            要被替换的字符串
	 * @param toString
	 *            用来替换的字符串
	 */
	public static void replaceFile(File file, String[] fromString,
			String[] toString) {
		String charset = FileUtil.getCharset(file.getPath());
		replaceFile(file, charset, fromString, toString);
	}

	/**
	 * 用指定编码读取文件,用指定字符串替换掉文件的字符串. 该方法能自动捕获异常并输出(使用log4j). 该方法不自动识别文件编码
	 * 
	 * @param file
	 *            文件
	 * @param charset
	 *            编码
	 * @param fromString
	 *            要被替换的字符串
	 * @param toString
	 *            用来替换的字符串
	 */

	public static void replaceFile(String file, String charset,
			String[] fromString, String[] toString) {
		replaceFile(new File(file), charset, fromString, toString);
	}

	/**
	 * 用指定编码读取文件,用指定字符串替换掉文件的字符串. 该方法能自动捕获异常并输出(使用log4j). 该方法不自动识别文件编码
	 * 
	 * @param file
	 *            文件
	 * @param charset
	 *            编码
	 * @param fromString
	 *            要被替换的字符串
	 * @param toString
	 *            用来替换的字符串
	 */

	public static void replaceFile(File file, String charset,
			String[] fromString, String[] toString) {
		InputStreamReader isr = null;
		BufferedReader br = null;
		OutputStreamWriter osw = null;
		try {
			isr = new InputStreamReader(new FileInputStream(file), charset);
			br = new BufferedReader(isr);
			StringBuilder sb = new StringBuilder();
			String s = "";
			String totalString = "";
			while ((s = br.readLine()) != null) {
				sb.append(s + LINE_SEPARATOR);
			}
			totalString = sb.toString();
			for (int j = 0; j < fromString.length; j++) {
				totalString = totalString
						.replaceAll(fromString[j], toString[j]);
			}
			osw = new OutputStreamWriter(new FileOutputStream(file), charset);
			// BufferedWriter bw=new BufferedWriter(osw);
			osw.write(totalString);
			osw.flush();
		} catch (FileNotFoundException e) {
			// e.printStackTrace();
			log.error("错误:文件" + file + "未找到!", e);
		} catch (IOException e) {
			// e.printStackTrace();
			log.error("错误:文件操作出错!", e);
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					// e.printStackTrace();
					log.error("错误:文件流关闭失败!", e);
				}
			if (isr != null)
				try {
					isr.close();
				} catch (IOException e) {
					// e.printStackTrace();
					log.error("错误:文件流关闭失败!", e);
				}
			if (osw != null)
				try {
					osw.close();
				} catch (IOException e) {
					// e.printStackTrace();
					log.error("错误:文件流关闭失败!", e);
				}
		}
	}

	/**
	 * 用指定编码读取指定文件路径下的文件,用指定字符串替换掉文件的字符串. 该方法能自动捕获异常并输出(使用log4j). 该方法不自动识别文件编码
	 * 
	 * @param path
	 *            文件路径
	 * @param charset
	 *            编码
	 * @param fromString
	 *            要被替换的字符串
	 * @param toString
	 *            用来替换的字符串
	 */

	public static void replaceDir(String path, String charset,
			String[] fromString, String[] toString) {
		File dir = new File(path);
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					replaceDir(path + FILE_SEPARATOR + tmp[i].getName(),
							charset, fromString, toString);
				} else {
					replaceFile(tmp[i], charset, toString, toString);
				}
			}
		}
	}

	/**
	 * 读取指定文件路径下的文件,用指定字符串替换掉文件的字符串. 该方法能自动捕获异常并输出(使用log4j). 该方法不能自动识别文件编码
	 * 
	 * @param path
	 *            文件路径
	 * @param fromString
	 *            要被替换的字符串
	 * @param toString
	 *            用来替换的字符串
	 */

	public static void replaceDir(String path, String[] fromString,
			String[] toString) {
		File dir = new File(path);
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					replaceDir(path + FILE_SEPARATOR + tmp[i].getName(),
							fromString, toString);
				} else {
					replaceFile(tmp[i], FileUtil.getCharset(tmp[i].getPath()),
							toString, toString);
				}
			}
		}
	}

	/**
	 * 返回文件类型, 该方法其实是返回文件的后缀名
	 * 
	 * @param fileName
	 *            文件名
	 * @return 文件类型(包括"."号), 若无".", 返回""空字符串
	 */

	public static String getFileType(String fileName) {
		String tmp = "";
		if (fileName.indexOf(".") > 0)
			tmp = fileName.substring(fileName.lastIndexOf("."));
		return tmp;
	}
	
	public static boolean forceDelete(File f) {
		boolean result = false;
		int tryCount = 0;
		while (!result && tryCount++ < 10) {
			log.debug("Try to delete file " + f.getName() + " cnt:" + tryCount);
			System.gc();
			result = f.delete();
		}
		return result;
	}   
	public static boolean forceDelete(String f) {
		return forceDelete(new File(f));
	}   

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -