Java文件生成zip文件

更新时间:2020-07-09 10:59:31 点击次数:890次
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private File file;

    private File zipFile;

    private String prefix;

    private String filepath;

    public File getFile() {
        return file;
    }

    public File getZipFile() {
        return zipFile;
    }

    /**
     * 创建文件
     *
     * @param filepath  文件路径,默认为/www/logs/temp/
     * @param prefix    文件名前缀,默认为tem_
     * @param extension 文件扩展名,默认为.txt
     * @param filename  文件名称,必填
     * @throws IOException
     */
    public void createFile(String filepath, String prefix, String extension, String filename) throws IOException {
        if (filename == null) {
            throw new IllegalArgumentException("filename is null");
        }
        this.prefix = prefix == null ? "tem_" : prefix;
        extension = extension == null ? ".txt" : extension;
        this.filepath = filepath == null ? "/www/logs/temp/" : filepath;
        File mkFile = new File(filepath);
        if (!mkFile.exists()) {
            mkFile.mkdirs();
        }
        logger.info("mkFile AbsolutePath: ", mkFile.getAbsolutePath());
        this.file = new File(filepath, filename + extension);
        this.file.createNewFile();
        logger.info("file AbsolutePath: ", file.getAbsolutePath());
    }

    /**
     * 创建临时文件
     *
     * @param prefix    文件名前缀,默认为tem_
     * @param extension 文件扩展名,默认为.txt
     * @param filepath  文件路径,非必填
     * @throws IOException
     */
    public void createTempFile(String prefix, String extension, String filepath) throws IOException {
        this.prefix = prefix == null ? "tem_" : prefix;
        extension = extension == null ? ".txt" : extension;
        this.filepath = filepath;
        if (filepath == null) {
            this.file = File.createTempFile(this.prefix, extension);
        } else {
            this.file = File.createTempFile(this.prefix, extension, new File(filepath));
        }
    }

    /**
     * 向文件中添加内容
     *
     * @param content
     */
    public void append(List<String> contents) {
        if (file == null) {
            return;
        }
        if (contents == null || contents.isEmpty()) {
            return;
        }
        try (FileWriter fileWriter = new FileWriter(file)) {    
for (String content : contents) {
fileWriter.write(content);
}
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文件转为zip压缩包
     *
     * @throws IOException
     */
    public void toZip() throws IOException {
        if (file == null) {
            return;
        }
        if (filepath == null) {
            this.zipFile = File.createTempFile(this.prefix, ".zip");
        } else {
            this.zipFile = File.createTempFile(this.prefix, ".zip", new File(filepath));
        }
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
             WritableByteChannel writableByteChannel = Channels.newChannel(zipOut);
             FileChannel fileChannel = new FileInputStream(file).getChannel()) {
            zipOut.putNextEntry(new ZipEntry(file.getName()));
            fileChannel.transferTo(0, file.length(), writableByteChannel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteFile() {
        if (file != null) {
            file.delete();
        }
        if (zipFile != null) {
            zipFile.delete();
        }
    }

    public InputStream getZipStream() throws FileNotFoundException {
        if (zipFile == null) {
            return null;
        }
        return new FileInputStream(zipFile);
    }

    /**
     * 存储本文件生成的zip
     *
     * @param fileStorage
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> T store(FileStorage fileStorage) throws Exception {
        InputStream zipStream = this.getZipStream();
        if (zipStream == null) {
            return null;
        }
        return exeStore(fileStorage, zipStream);
    }

    /**
     * 存储自定义内容
     *
     * @param fileStorage
     * @param stream
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> T store(FileStorage fileStorage, InputStream stream) throws Exception {
        if (stream == null) {
            return null;
        }
        return exeStore(fileStorage, stream);
    }

    private <T> T exeStore(FileStorage fileStorage, InputStream stream) throws Exception {

        T obj;
        try {
            obj = fileStorage.doStore(stream);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
        return obj;
    }

    /**
     * 文件存储,自实现存储方式
     */
    public interface FileStorage {
        <T> T doStore(InputStream zipStream) throws Exception;
    }

}


本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是一个个人学习交流的平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽,造成漏登,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

回到顶部
嘿,我来帮您!