Springboot系统启动自动解压代码实例

最近做的项目使用到了文件型数据库derby,实现了系统启动时自动解压derby数据库文件的功能。

以下是参考代码

 

springboot启动类

/**
 * 
 */
package com.tonny.xxxx;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.zip.ZipException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tonny.xxxx.config.ConfigConstants;
import com.tonny.xxxx.util.ZipUtils;



public class SpringBootStartApplication extends SpringBootServletInitializer {

	public static int Installed = 0;
	public static String webappAbsolutePath = "";
	
	
	
	
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return builder.sources(Application.class);
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		webappAbsolutePath = servletContext.getRealPath("");
		unZipDerbyInitDB();
        super.onStartup(servletContext);
	}
	
	private void unZipDerbyInitDB() {
		String dataSourceUrl = ConfigConstants.getConfig("spring.datasource.url", "");
		if (dataSourceUrl.contains("derby")) {
			
			if (StringUtils.isBlank(webappAbsolutePath)) {
	        	webappAbsolutePath = getRealPath();
	        }
			try {
                executeUnzipService(dataSourceUrl);
            } catch (Throwable e) {
            }
		} else {
			return;
		}
    	
	}

	private String getRealPath() {
        String realPath = "";
        String rPath = this.getClass().getClassLoader().getResource("/").getPath();
        if (rPath != null) {
            int i = rPath.indexOf("WEB-INF");
            if (i > 0) {
                realPath = rPath.substring(0, i - 1);
            }
        }
        return realPath;
    }

    private void executeUnzipService(String dataSourceUrl) {
    	String unzipPath = "";
    	if (!StringUtils.isBlank(dataSourceUrl)) {
    		unzipPath = dataSourceUrl.substring(dataSourceUrl.indexOf("derby:")+6, dataSourceUrl.indexOf(";"));
    	}
    	if (!new File(unzipPath).exists()) {
    		boolean result = new File(unzipPath).mkdirs();
    		if (result) {
	    		String derbyDbZipPath = webappAbsolutePath + "WEB-INF/classes/db/derby";
	    		try {
	    			ZipUtils.unZipDirectory(derbyDbZipPath, unzipPath);
	    		} catch (ZipException e) {
	    		} catch (IOException e) {
	    		}
    		} else {
    			System.out.println("创建文件夹失败,解压失败!");
    		}
    	}
    }

}


 ZipUtils.java

package com.tonny.device.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;


public class ZipUtils {

    public static final int BUFFER_SIZE = 4096;


    public ZipUtils() {}

    public static void unZipDirectory(String zipFileDirectory, String outputDirectory)
        throws ZipException, IOException {
        File file = new File(zipFileDirectory);
        File[] files = file.listFiles();
        for (int i = 0; files != null && i < files.length; i++) {
            if (files[i].getName().endsWith(".zip")) {
                unzip(zipFileDirectory + File.separator + files[i].getName(), outputDirectory);
            }
        }
    }

    public static void unzip(String filename, String startsWith, String outputDirectory)
        throws ZipException, IOException {
        if (startsWith == null) {
            startsWith = "";
        }
        File dir = new File(outputDirectory);
        dir.mkdir();
        List<ZipEntry> entries = new ArrayList<ZipEntry>();
        ZipFile zipFile = new ZipFile(filename);
        @SuppressWarnings("unchecked")
        Enumeration<ZipEntry> enu = (Enumeration<ZipEntry>)zipFile.entries();
        while (enu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry)enu.nextElement();
            if (entry.getName().startsWith(startsWith)) {
                if (entry.isDirectory()) {
                    String fileName = entry.getName().substring(0, entry.getName().length() - 1);
                    String directoryPath = outputDirectory + File.separator + fileName;
                    File directory = new File(directoryPath);
                    directory.mkdir();
                }
                entries.add(entry);
            }
        }
        unzip(zipFile, entries, startsWith, outputDirectory);
    }

    public static void unzip(String filename, String outputDirectory) throws ZipException, IOException {
        unzip(filename, "", outputDirectory);
    }

    private static void unzip(ZipFile zipFile, List<ZipEntry> entries, String startsWith, String outputDirectory)
        throws IOException {

        Iterator<ZipEntry> it = entries.iterator();
        while (it.hasNext()) {
            ZipEntry zipEntry = (ZipEntry)it.next();
            if (!zipEntry.isDirectory()) {
                unzipFiles(zipFile, zipEntry, outputDirectory);
            }
        }
    }

    // 读取压缩文件中的内容名称
    public static List<String> readZipFile(String file) throws Exception {
        List<String> list = new ArrayList<String>();
        InputStream in = null;
        @SuppressWarnings("resource")
        ZipInputStream zin = null;
        try {
        	in = new BufferedInputStream(new FileInputStream(file));
        	zin = new ZipInputStream(in);
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {
                if (ze.isDirectory()) {
                } else {
                    String zeName = new String(ze.getName().getBytes("iso-8859-1"), "utf-8");
                    list.add(zeName);
                }
            }

        } catch (Exception ex) {
            throw ex;
        } finally {
        	if(zin != null) {
        		zin.closeEntry();
        	}
        	if(in != null) {
        		in.close();
        	}
        }
        return list;
    }

    public static void unzipFiles(ZipFile zipFile, ZipEntry zipEntry, String outputDirectory) {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        try {
            byte[] data = new byte[BUFFER_SIZE];
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            String entryName = zipEntry.getName();
            entryName = new String(entryName.getBytes("GBK"));
            fos = new FileOutputStream(outputDirectory + File.separator + entryName);
            if (zipEntry.isDirectory()) {

            } else {
                int count = 0;
                while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
                    fos.write(data, 0, count);
                }
                fos.flush();
                fos.close();
            }
        } catch (Throwable e) {
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Throwable e) {
            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (Throwable e) {
            }
        }
    }
}

/**
 * 使用多线程,提高效率
 * 
 * @author 立强
 *
 */
class MultiThreadEntry implements Runnable {

    private BufferedInputStream bis;
    private ZipEntry zipEntry;
    private String outputDirectory;

    public MultiThreadEntry(ZipFile zipFile, ZipEntry zipEntry, String outputDirectory) throws IOException {
        this.zipEntry = zipEntry;
        this.outputDirectory = outputDirectory;
        bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
    }

    public void run() {
        try {
            unzipFiles(zipEntry, outputDirectory);
        } catch (IOException e) {
            try {
                bis.close();
            } catch (IOException e1) {
            }
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
            }
        }
    }

    public void unzipFiles(ZipEntry zipEntry, String outputDirectory) throws IOException {
        byte[] data = new byte[ZipUtils.BUFFER_SIZE];
        String entryName = zipEntry.getName();
        entryName = new String(entryName.getBytes("GBK"));
        // entryName = entryName.substring(startsWith.length());
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try{
        fos = new FileOutputStream(outputDirectory + File.separator + entryName);
        if (zipEntry.isDirectory()) {

        } else {
            bos = new BufferedOutputStream(fos, ZipUtils.BUFFER_SIZE);
            int count = 0;
            while ((count = bis.read(data, 0, ZipUtils.BUFFER_SIZE)) != -1) {
                bos.write(data, 0, count);
            }
            
        	}
        }catch( Exception e ){
        }finally{
        	if(bos != null){
        		bos.flush();
                bos.close();
        	}
        	if (fos != null) {
        		fos.flush();
        		fos.close();
        	}
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LemonSmile_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值