文件操作工具集

package com.sinotrans.filesystem.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtil {

	protected static final Log log = LogFactory.getLog(FileUtil.class);

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static byte[] file2Byte(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (IOException e) {
			log.error("", e);
		}
		return buffer;
	}

	/**
	 * 
	 * @param buf
	 * @param path
	 */
	public static void byte2File(byte[] buf, String path)
			throws FileNotFoundException, IOException {

		FileOutputStream fileOutputStream = new FileOutputStream(path);
		fileOutputStream.write(buf);
		fileOutputStream.close();

	}

	public static void str2File(String str, String path) throws IOException {
		FileOutputStream fileOutputStream = new FileOutputStream(path);
		fileOutputStream.write(str.getBytes());
		fileOutputStream.close();
	}

	public static boolean moveFile(File srcFile, File desDir)
			throws FileNotFoundException {
		if (!desDir.exists())
			desDir.mkdirs();
		if (!srcFile.exists())
			throw new FileNotFoundException("文件" + srcFile.getPath() + "已经被移除");
		String fileName = srcFile.getName();
		if (fileName.contains(".apk") || fileName.contains(".ipa")) {
			String attachName = "content"
					+ fileName.substring(fileName.indexOf("."),
							fileName.length());
			File des = new File(desDir, attachName);
			Boolean b = srcFile.renameTo(des);
			return b;
		} else {
			File des = new File(desDir, srcFile.getName());
			Boolean b = srcFile.renameTo(des);
			return b;
		}
	}

	/**
	 * @描述:获取指定文件夹下的文件(目录)名称
	 * @param path
	 *            目录地址,绝对路径
	 * @return
	 */
	public static List<String> getFilesName(String path) {
		List<String> list = new ArrayList<String>();
		File file = new File(path);
		File[] array = file.listFiles();
		for (int i = 0; i < array.length; i++) {
			if (array[i].isFile()) {
				String fileName = array[i].getName(); // 获取文件名称
				list.add(fileName);
			} else if (array[i].isDirectory()) {
				String fileName = array[i].getName(); // 获取目录名称
				list.add(fileName);
			}
		}
		return list;
	}

	/**
	 * @描述 删除文件以及空文件夹
	 * @param filePath
	 *            要删除的文件或者空文件夹地址
	 * @return
	 */
	public static boolean delFile(String filePath) {
		File file = new File(filePath);
		// 判断是否为文件
		if (file.isFile()) { // 为文件时调用删除文件方法
			return file.delete();
		} else {
			return false;
		}
	}

	/**
	 * @描述:删除指定目录以及子目录和文件
	 * @param filepath
	 *            要删除的目录地址
	 */
	public static boolean delFolder(String filepath) {
		File f = new File(filepath);
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				return f.delete();
			} else {// 若有则把文件放进数组,并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						delFolder(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();
				}
				return true;
			}
		} else {
			return false;
		}
	}

	/**
	 * @描述 创建目录
	 * @param rootPath
	 *            文件的根目录 例如:D:\ROOT\
	 * @param folderName
	 *            需要创建文件的名称 例如: NAME
	 * @return
	 */
	public static boolean createFolder(String rootPath, String folderName) {
		File apkScr = new File(rootPath, folderName);
		if (!apkScr.exists()) {
			return apkScr.mkdirs();
		} else {
			return false;
		}
	}

	/**
	 * @描述 将源目标文件拷贝到指定的目标目录文件下
	 * @param sourcePath
	 *            源文件地址
	 * @param targetPath
	 *            目标文件地址
	 * @return
	 */
	public static boolean copyFile(String sourcePath, String targetPath) {
		try {
			InputStream ips = readFile(sourcePath);
			saveFile(ips, targetPath);
			ips.close();
		} catch (IOException e1) {
			e1.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * @描述 复制一个目录及其子目录、文件到另外一个目录
	 * 
	 * @param srcDirectory
	 *            源目录
	 * @param destDirectory
	 *            目标目录
	 * @throws IOException
	 */
	public static void copyFolder(File srcDirectory, File destDirectory)
			throws IOException {
		if (srcDirectory.isDirectory()) {
			if (!destDirectory.exists()) {
				destDirectory.mkdir();
			}
			String files[] = srcDirectory.list();
			for (String file : files) {
				File srcFile = new File(srcDirectory, file);
				File destFile = new File(destDirectory, file);
				// 递归复制
				copyFolder(srcFile, destFile);
			}
		} else {
			InputStream in = new FileInputStream(srcDirectory);
			OutputStream out = new FileOutputStream(destDirectory);

			byte[] buffer = new byte[1024];

			int length;

			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			in.close();
			out.close();
		}
	}

	/**
	 * @描述 读取文件,返回流
	 * @param path
	 *            文件存放路径
	 * @return 文件流
	 */
	public static InputStream readFile(String path) {
		// File file=new File(basePath+File.separator+path);
		try {
			FileInputStream inputStream = new FileInputStream(path);
			return inputStream;
		} catch (FileNotFoundException e) {
			log.error("", e);
		}
		return null;
	}

	/**
	 * @描述 根据流保存文件 <方法功能详述(简单方法可不必详述)>
	 * @param is
	 *            输入流
	 * @param path
	 *            文件的绝对路径
	 * @return File 创建好的文件对象
	 * 
	 */
	public static File saveFile(InputStream is, String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		} else {
			String flod = file.getParent();
			try {
				FileUtils.forceMkdir(new File(flod));
			} catch (IOException e) {
				log.error("", e);
			}
		}
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(file);
			IOUtils.copy(is, fileOutputStream);
		} catch (Exception e) {
			log.error("", e);
		} finally {
			IOUtils.closeQuietly(is);
			IOUtils.closeQuietly(fileOutputStream);
		}
		return file;
	}

	/**
	 * @描述 重命名文件夹名称
	 * @param path
	 *            需要重命名文件夹的父目录地址
	 * @param oldname
	 *            需要重命名的文件夹名称
	 * @param newname
	 *            新的文件夹名称
	 */
	public static void renameFile(String path, String oldname, String newname) {
		if (!oldname.equals(newname)) {// 新的文件名和以前文件名不同时,才有必要进行重命名
			File oldfile = new File(path + File.separator + oldname);
			File newfile = new File(path + File.separator + newname);
			if (!oldfile.exists()) {
				return;// 重命名文件不存在
			}
			if (newfile.exists())// 若在该目录下已经有一个文件和新文件名相同,则不允许重命名
				return;
			else {
				oldfile.renameTo(newfile);
				return;
			}
		} else {
			return; // oldname 和 newname相同
		}
	}
}

猜你喜欢

转载自blog.csdn.net/u014505277/article/details/50629747
今日推荐