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 entries = new ArrayList();
        ZipFile zipFile = new ZipFile(filename);
        @SuppressWarnings("unchecked")
        Enumeration enu = (Enumeration)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 entries, String startsWith, String outputDirectory)
        throws IOException {

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

    // 读取压缩文件中的内容名称
    public static List readZipFile(String file) throws Exception {
        List list = new ArrayList();
        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();
        	}
        }
    }

}

你可能感兴趣的:(spring,boot,后端,java)