All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.soento.core.util.FileUtil Maven / Gradle / Ivy

package com.soento.core.util;

import com.soento.core.enums.Audio;
import com.soento.core.enums.Image;
import com.soento.core.enums.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @author soento
 */
@Slf4j
public final class FileUtil extends FileUtils {

    /**
     * 文档压缩
     *
     * @param file 需要压缩的文件或目录
     * @param dest 压缩后的文件名称
     */
    public static void zip(File file, String dest) {
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest))) {
            zipFile(file, zos, "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文档解压
     *
     * @param source 需要解压缩的文档名称
     * @param path   需要解压缩的路径
     */
    public static void unZip(File source, String path) {
        ZipEntry zipEntry;
        createPaths(path);
        // 实例化ZipFile,每一个zip压缩文件都可以表示为一个ZipFile
        // 实例化一个Zip压缩文件的ZipInputStream对象,可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象
        try (
                ZipFile zipFile = new ZipFile(source);
                ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))
        ) {
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                File temp = new File(path + "/" + fileName);
                if (!temp.getParentFile().exists()) {
                    boolean success = temp.getParentFile().mkdirs();
                    if (!success) {
                        log.error("文件创建失败");
                    }
                }
                try (OutputStream os = new FileOutputStream(temp);
                     // 通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
                     InputStream is = zipFile.getInputStream(zipEntry)) {
                    int len;
                    while ((len = is.read()) != -1) {
                        os.write(len);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void zipFile(File inFile, ZipOutputStream zos, String dir) throws IOException {
        if (inFile.isDirectory()) {
            File[] files = inFile.listFiles();
            if (Objects.nonNull(files) && files.length > 0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    zipFile(file, zos, name);
                }
            }
        } else {
            String entryName;
            if (!"".equals(dir)) {
                entryName = dir + "/" + inFile.getName();
            } else {
                entryName = inFile.getName();
            }
            ZipEntry entry = new ZipEntry(entryName);
            zos.putNextEntry(entry);
            try (InputStream is = new FileInputStream(inFile)) {
                int len;
                while ((len = is.read()) != -1) {
                    zos.write(len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建多级目录.
     *
     * @param paths 需要创建的目录
     * @return 是否成功
     */
    private static boolean createPaths(String paths) {
        File dir = new File(paths);
        return !dir.exists() && dir.mkdir();
    }

    private static void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */
        if (file.isDirectory()) {
            compressDirectory(file, out, basedir);
        } else {
            compressFile(file, out, basedir);
        }
    }

    /**
     * 压缩一个目录
     */
    private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists()) {
            return;
        }
        File[] files = dir.listFiles();
        if (files == null || files.length <= 0) {
            log.warn("compress directory.files is empty");
            return;
        }
        for (File file : files) {
            compress(file, out, basedir + dir.getName() + File.separator);
        }
    }

    private static void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {

            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            final int maxLength = 8192;
            byte[] data = new byte[maxLength];
            while ((count = bis.read(data, 0, maxLength)) != -1) {
                out.write(data, 0, count);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] toByteArray(File f) {
        if (!f.exists()) {
            throw new RuntimeException(f.getPath());
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
            }
            return byteBuffer.array();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            StreamUtil.close(channel);
            StreamUtil.close(fs);
        }
    }

    /**
     * 根据给定的文件名,获取其扩展名
     *
     * @param filename 文件名
     * @return 扩展名
     */
    public static String extension(String filename) {
        return FilenameUtils.getExtension(filename);
    }

    /**
     * 根据给定的扩展名,获取文件类型
     *
     * @param extension 扩展名
     * @return 文件类型
     */
    public static String type(String extension) {
        if (Image.has(extension)) {
            return "image";
        } else if (Audio.has(extension)) {
            return "audio";
        } else if (Video.has(extension)) {
            return "video";
        } else {
            return "file";
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy