Java 操作文件 文件夹

package lnsoft.utility.FileUtil;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.apache.log4j.Logger;

import lnsoft.utility.file.FileHelper;
import lnsoft.utility.transformat.FormatDate;

public class FileUtil {
    static Logger logger; // Logger.getLogger(Log.class.getName());

    /**
     * 获得指定文件的byte数组
     * 
     * @throws FileNotFoundException
     */
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return buffer;
    }

    /**
     * 删除指定文件
     * 
     * @Title deleteFile
     * @Date 2016-9-7 上午9:14:46
     * @author LUANXINWEI
     * @Description
     * @param path
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        file.delete();
    }

    /**
     * 根据byte数组,生成文件
     */
    public static void getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在

            } else {
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据路径删除指定的目录或文件,无论存在与否
     * 
     * @param sPath
     *            要删除的目录或文件
     * @param delFile
     *            true删除文件目录 ; false删除文件
     * @return 删除成功返回 true,否则返回 false。
     */
    public static boolean DeleteFolder(String sPath, boolean delFile) {
        boolean flag = false;
        File file = new File(sPath);
        // 判断目录或文件是否存在
        if (!file.exists()) { // 不存在返回 false
            return flag;
        } else {
            if (!delFile) {
                // 判断是否为文件
                if (file.isFile()) { // 为文件时调用删除文件方法
                    return deleteFiles(sPath);
                }
            }
            // 为目录时调用删除目录方法
            if (delFile) {
                return deleteDirectory(sPath);
            }
        }
        return flag;
    }

    /**
     * 删除单个文件
     * 
     * @param sPath
     *            被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFiles(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除目录(文件夹)以及目录下的文件
     * 
     * @param sPath
     *            被删除目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果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 = deleteFiles(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除空目录
     * 
     * @param dir
     *            将要删除的目录路径
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * 
     * @param dir
     *            将要删除的文件目录
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }

    /**
     * 删除目录下的所有文件(不包含参数中传递过来的文件夹)
     * 
     * @Title clearDir
     * @Date 2016-9-6 下午1:30:16
     * @author LUANXINWEI
     * @Description
     * @param sPath
     * @return
     */
    public static boolean clearDir(String sPath) {
        File dir = new File(sPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                File dirc = new File(dir + "/" + children[i]);
                deleteDir(dirc);
            }
        }
        // 目录此时为空,可以删除
        return true;
        // return dir.delete();
    }

    public static void main(String[] args) {
        // clearDir("G:/demo/test");
        logToText("qunimade", "1231321231.txt");
    }

    /**
     * 创建文件夹
     * 
     * @Title createFile
     * @Date 2016-9-6 下午1:34:51
     * @author LUANXINWEI
     * @Description
     * @param path
     */
    public static void createFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /*
     * 判断文件是否存在
     */
    public static boolean fileIsExsit(String path) {
        File file = new File(path);
        // 判断是否为文件
        if (file.isFile()) {
            return true;
        }
        return false;
    }

    /**
     * 
     * @Title logToText
     * @Date 2017年6月12日 上午11:48:28
     * @author WEIL
     * @Description 打印日志到txt文档
     * @param log
     */
    public static void logToText(String log, String fileName) {
        File file = new File(fileName);
        FileWriter fw = null;
        FileInputStream fis = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(fileName, true);
            fis = new FileInputStream(file);
            double fileStreamsize = fis.available();
            double filesize = fileStreamsize / 1024.0 / 1024.0;
            if (filesize > 100) {
                FileHelper.writeTxtFile("", fileName, "", false);
            }
            bw = new BufferedWriter(fw);
            bw.write(FormatDate.formatDate("yyyy-MM-dd HH:mm:ss", new Date()) + ":" + log + "\r\n ");// 往已有的文件上添加字符串
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值