java 文件处理工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件处理工具类
 * 
 */
public class FileUtil {

	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	// add by zhaolei 拷贝文件
	@SuppressWarnings("unused")
	public static void copyFile(String oldPath, String newPath) {
		int bytesum = 0;
		int byteread = 0;
		
		File oldfile = new File(oldPath);
		if (oldfile.exists()) { // 文件存在时
			try (
				InputStream inStream = new FileInputStream(oldPath);
				FileOutputStream fs = new FileOutputStream(newPath);	
			) {
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
			} catch (IOException e) {
				logger.error("", e);
			}
		} else {
			logger.info("文件不存在!文件目录为:" + oldfile.getAbsolutePath());
		}
	}

	// add by zhaolei 剪切文件
	@SuppressWarnings("unused")
	public static void cutFile(String oldPath, String newPath) {
		int bytesum = 0;
		int byteread = 0;
		File oldfile = new File(oldPath);
		if (oldfile.exists()) { // 文件存在时
			try (
				InputStream inStream = new FileInputStream(oldPath);
				FileOutputStream fs = new FileOutputStream(newPath);
			) {
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				
			} catch (IOException e) {
				logger.error("", e);
			}
			oldfile.delete();// 删除原文件
		} else {
			logger.info("文件不存在!文件目录为:" + oldfile.getAbsolutePath());
		}
	}

	public static boolean deleteDirectory(String path) {
		// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!path.endsWith(File.separator)) {
			path = path + File.separator;
		}
		File dirFile = new File(path);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = files[i].delete();
				if (!flag) {
					break;
				}
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
		}
		if (!flag) {
			return false;
		}
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

}

  

posted @ 2021-03-04 16:41  南山下的采药人  阅读(98)  评论(0编辑  收藏  举报