java 文件操作工具类

java 文件操作工具类

import java.io.*;
import java.net.URLDecoder;
import java.util.logging.Logger;

/**
 * 文件操作工具类
 *
 * @author Administrator
 */
public class FileUtils {

    private static Logger LOG = Logger.getLogger("FileUtils");

    /**
     * 获取备份文件路径
     *
     * @param path
     * @return
     */
    public static String getBak(String path) {
        return path + ".bak";
    }

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

    /**
     * 创建文件
     *
     * @param destFileName
     * @return
     */
    public static boolean createFile(String destFileName) {
        File file = new File(destFileName);
        if (file.exists()) {
            LOG.info("创建单个文件" + destFileName + "失败,目标文件已存在!");
            return false;
        }
        if (destFileName.endsWith(File.separator)) {
            LOG.info("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
            return false;
        }
        //判断目标文件所在的目录是否存在  
        if (!file.getParentFile().exists()) {
            //如果目标文件所在的目录不存在,则创建父目录  
            LOG.info("目标文件所在目录不存在,准备创建它!");
            if (!file.getParentFile().mkdirs()) {
                LOG.info("创建目标文件所在目录失败!");
                return false;
            }
        }
        //创建目标文件  
        try {
            if (file.createNewFile()) {
                LOG.info("创建单个文件" + destFileName + "成功!");
                return true;
            } else {
                LOG.info("创建单个文件" + destFileName + "失败!");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOG.info("创建单个文件" + destFileName + "失败!" + e.getMessage());
            return false;
        }
    }

    /**
     * 创建文件夹
     *
     * @param destDirName
     * @return
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            LOG.info("创建目录" + destDirName + "失败,目标目录已经存在");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录  
        if (dir.mkdirs()) {
            LOG.info("创建目录" + destDirName + "成功!");
            return true;
        } else {
            LOG.info("创建目录" + destDirName + "失败!");
            return false;
        }
    }


    /**
     * 创建临时文件
     *
     * @param prefix
     * @param suffix
     * @param dirName
     * @return
     */
    public static String createTempFile(String prefix, String suffix, String dirName) {
        File tempFile = null;
        if (dirName == null) {
            try {
                //在默认文件夹下创建临时文件  
                tempFile = File.createTempFile(prefix, suffix);
                //返回临时文件的路径  
                return tempFile.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
                LOG.info("创建临时文件失败!" + e.getMessage());
                return null;
            }
        } else {
            File dir = new File(dirName);
            //如果临时文件所在目录不存在,首先创建  
            if (!dir.exists()) {
                if (!createDir(dirName)) {
                    LOG.info("创建临时文件失败,不能创建临时文件所在的目录!");
                    return null;
                }
            }
            try {
                //在指定目录下创建临时文件  
                tempFile = File.createTempFile(prefix, suffix, dir);
                return tempFile.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
                LOG.info("创建临时文件失败!" + e.getMessage());
                return null;
            }
        }
    }

    /**
     * 复制单个文件
     *
     * @param srcFileName  待复制的文件名
     * @param destFileName 目标文件名
     * @param overlay      如果目标文件存在,是否覆盖
     * @return 如果复制成功返回true,否则返回false
     */
    public static boolean copyFile(String srcFileName, String destFileName,
                                   boolean overlay) {
        File srcFile = new File(srcFileName);

        // 判断源文件是否存在  
        if (!srcFile.exists()) {
            return false;
        } else if (!srcFile.isFile()) {
            return false;
        }

        // 判断目标文件是否存在  
        File destFile = new File(destFileName);
        if (destFile.exists()) {
            // 如果目标文件存在并允许覆盖  
            if (overlay) {
                // 删除已经存在的目标文件,无论目标文件是目录还是单个文件  
                new File(destFileName).delete();
            }
        } else {
            // 如果目标文件所在目录不存在,则创建目录  
            if (!destFile.getParentFile().exists()) {
                // 目标文件所在目录不存在  
                if (!destFile.getParentFile().mkdirs()) {
                    // 复制文件失败:创建目标文件所在目录失败  
                    return false;
                }
            }
        }

        // 复制文件  
        int byteread = 0; // 读取的字节数  
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];

            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 复制整个目录的内容
     *
     * @param srcDirName  待复制目录的目录名
     * @param destDirName 目标目录名
     * @param overlay     如果目标目录存在,是否覆盖
     * @return 如果复制成功返回true,否则返回false
     */
    public static boolean copyDirectory(String srcDirName, String destDirName,
                                        boolean overlay) {
        // 判断源目录是否存在  
        File srcDir = new File(srcDirName);
        if (!srcDir.exists()) {
            return false;
        } else if (!srcDir.isDirectory()) {
            return false;
        }

        // 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符  
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        File destDir = new File(destDirName);
        // 如果目标文件夹存在  
        if (destDir.exists()) {
            // 如果允许覆盖则删除已存在的目标目录  
            if (overlay) {
                new File(destDirName).delete();
            } else {
                return false;
            }
        } else {
            // 创建目的目录  
            System.out.println("目的目录不存在,准备创建。。。");
            if (!destDir.mkdirs()) {
                System.out.println("复制目录失败:创建目的目录失败!");
                return false;
            }
        }

        boolean flag = true;
        File[] files = srcDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 复制文件  
            if (files[i].isFile()) {
                flag = copyFile(files[i].getAbsolutePath(),
                        destDirName + files[i].getName(), overlay);
                if (!flag)
                    break;
            } else if (files[i].isDirectory()) {
                flag = copyDirectory(files[i].getAbsolutePath(),
                        destDirName + files[i].getName(), overlay);
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            return false;
        } else {
            return true;
        }
    }

    public static String getFileExt(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    public static void main(String[] args) {
        //创建目录  
        String dirName = "D:/work/temp/temp0/temp1";
        FileUtils.createDir(dirName);
        //创建文件  
        String fileName = dirName + "/temp2/tempFile.txt";
        FileUtils.createFile(fileName);
        //创建临时文件  
        String prefix = "temp";
        String suffix = ".txt";
        for (int i = 0; i < 10; i++) {
            LOG.info("创建了临时文件:"
                    + FileUtils.createTempFile(prefix, suffix, dirName));
        }
        //在默认目录下创建临时文件  
        for (int i = 0; i < 10; i++) {
            LOG.info("在默认目录下创建了临时文件:"
                    + FileUtils.createTempFile(prefix, suffix, null));
        }
    }

    public static InputStream getResourceAsStream(String path) {
        InputStream in = null;
        try {
            in = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return in;
    }

    public static File getResourceAsFile(String path) {
        try {
            return new File(URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource(path).getFile(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值