常用的File工具类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qfashly/article/details/79499227

转载请注明:https://blog.csdn.net/qfashly/article/details/79499227

public class FileUtils {
    private static Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 读取文件
     * @param fileName
     * @return
     */
    public static String readFile(String fileName) {
        String str = null;
        //获取通道
        FileInputStream fis = null;
        FileChannel channel = null;
        try {
            fis = new FileInputStream(fileName);
            channel = fis.getChannel();
            //指定缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);
            //将通道中的数据读到缓冲区中
            channel.read(buf);
            byte[] arr = buf.array();
            str = new String(arr);
        } catch (FileNotFoundException e) {
            log.error(fileName+"文件不存在", e);
        } catch (IOException e) {
            log.error("IO异常", e);
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ee) {
                ee.printStackTrace();
                log.error("IO异常", ee);
            }
        }
        return str.toString();
    }

    /**
     * nio写文件
     * @param fileName
     * @param content
     * @return
     */
    public static void writeFile(String fileName, String content) {
        //获取通道
        FileOutputStream fos = null;
        FileChannel channel = null;
        ByteBuffer buffer = null;
        try {
            fos = new FileOutputStream(fileName);
            channel = fos.getChannel();
            buffer = ByteBuffer.wrap(content.getBytes());
            //将内容写到缓冲区
            fos.flush();
            channel.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(fileName+"文件不存在", e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IO异常", e);
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
        }
    }

    /**
     * 复制文件
     * @param sourceFile
     * @param desFile
     */
    public static void copyFile(String sourceFile, String desFile) {
        // 获取源文件和目标文件的输入输出流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel fisChannel = null;
        FileChannel fosChannel = null;
        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(desFile);
            // 获取输入输出通道
            fisChannel = fis.getChannel();
            fosChannel = fos.getChannel();
            // 创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (true) {
                // clear方法重设缓冲区,使它可以接受读入的数据
                buffer.clear();
                // 从输入通道中将数据读到缓冲区
                int r = fisChannel.read(buffer);
                // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
                if (r == -1) {
                    break;
                }
                // flip方法让缓冲区可以将新读入的数据写入另一个通道
                buffer.flip();
                // 从输出通道中将数据写入缓冲区
                fosChannel.write(buffer);
            }
            fisChannel.close();
            fosChannel.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("文件不存在", e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IO异常", e);
        } finally {
            try {
                if (fisChannel != null) {
                    fisChannel.close();
                }
                if (fosChannel != null) {
                    fosChannel.close();
                }
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
        }
    }

    /**
     * @Title: deleteDir
     * @Description: 递归删除目录下的所有文件及子目录下所有文件
     * @param dir
     * @return
     * @author chenxy
     * @date 2018-1-17 下午3:25:01
     */
    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: deleteFile
     * @Description: 除文件夹中指定的文件类型,如果有文件夹则不删除文件夹中的文件
     * @param path
     * @param fileType
     * @author chenxy
     * @date 2018-1-18 上午9:38:46
     */
    public static void deleteFile(String path, String fileType){
        if(StringUtils.isNullOrBlank(path)){
            return;
        }
        File file = new File(path);
        if(file.isFile()){//文件
            File[] listFiles = {file};
            deleteFileByType(listFiles, fileType);
        }
        if(file.isDirectory()){//文件夹
            File[] listFiles = file.listFiles();
            deleteFileByType(listFiles, fileType);
        }
    }

    /**
     * @Title: cycleDeleteFile
     * @Description: 循环删除文件夹中指定的文件类型
     * @param path
     * @param fileType
     * @author chenxy
     * @date 2018-1-18 上午9:37:49
     */
    public static void cycleDeleteFile(String path, String fileType){
        if(StringUtils.isNullOrBlank(path)){
            return;
        }
        File file = new File(path);
        if(file.isFile()){//文件
            File[] listFiles = {file};
            deleteFileByType(listFiles, fileType);
        }
        if(file.isDirectory()){//文件夹
            String[] files = file.list();
            for(String filePath : files){
                cycleDeleteFile(file.getPath() + File.separator + filePath, fileType);
            }
        }
    }

    /**
     * @Title: deleteFileByType
     * @Description: 判断文件是否是指定的类型,如果是则删除之
     * @param listFiles
     * @param fileType
     * @author chenxy
     * @date 2018-1-18 上午9:39:24
     */
    public static void deleteFileByType(File[] listFiles, String fileType) {
        if(listFiles == null || listFiles.length <= 0){
            return;
        }
        String suffixName = "";
        for(File file : listFiles){
            if(!file.isFile()){//文件
                continue;
            }
            suffixName = getSuffixName(file);
            if(StringUtils.isNullOrBlank(suffixName)){
                continue;
            }
            if(fileType.equals(suffixName)){
                if(!file.delete()){
                    log.error("删除" + file.getPath() + "失败");
                }
            }
        }
    }

    /**
     * @Title: getSuffixName
     * @Description: 放回文件的后缀名, 如JPEG:FFD8FF
     * @param file
     * @return
     * @author chenxy
     * @date 2018-1-18 上午9:45:03
     */
    public static String getSuffixName(File file){
        if(!file.isFile()){
            return null;
        }
        FileInputStream is = null;
        byte[] src = new byte[3];
        StringBuilder sBuilder = null;
        String hv = null;
        try {
            is = new FileInputStream(file);
            src = new byte[3];
            is.read(src, 0, src.length);
            is.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        if (src == null || src.length <= 0) {
            return null;
        }
        sBuilder = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sBuilder.append(0);
            }
            sBuilder.append(hv);
        }
        if(sBuilder.length() <= 0){
            return null;
        }
        return sBuilder.toString().toUpperCase();
    }

    /**
     * @Title: getFile
     * @Description: 获取文件夹中所有的文件
     * @param path
     * @param fileList
     * @author chenxy
     * @date 2018-1-18 上午10:32:13
     */
    public static void getFile(String path, ArrayList<File> fileList){
        File file = new File(path);
        if(file.isFile()){
            fileList.add(file);
            return;
        }
        String[] files = file.list();
        for(String filePath : files){
            getFile(file.getPath() + File.separator + filePath, fileList);
        }
    }

    public static void main(String[] args){
        String path = "D:\\Log";
        // 776569 log
        // 89504E png

        cycleDeleteFile(path, AppContant.SuffixName.LOG);


        /*String path = "D:\\Log";
        ArrayList<File> fileList = new ArrayList<File>();
        getFile(path, fileList);

        Map<String, String> map = new HashMap<String, String>();
        String[] strs = null;
        for(File file : fileList){
            strs = file.getPath().split("\\.");
            if(strs.length < 2){
                continue;
            }
            map.put(strs[strs.length - 1], getSuffixName(file));
            //System.out.println("  " + getSuffixName(file) + " = " + file.getPath());
        }
        for(Entry<String, String> entry : map.entrySet()){
            System.out.println("    " + entry.getKey() + " = " + entry.getValue());
        }*/

    }
}

猜你喜欢

转载自blog.csdn.net/qfashly/article/details/79499227