Java文件生成zip文件

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 
     * @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 
     * @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;
    }

}

你可能感兴趣的:(java工具)