模拟maven的管理jar包。使用文件签名。非版本号

说明

    在家整理以前的项目时,并想备份到网盘,发现项目很多都不是使用maven的老项目,感觉jar非常多,而且重复也比较多,所以就想把那些重复的jar去掉,并可以还原。

使用缓存 java  Jars  cache  是否清理jar 地址
 还原      java Jars  restore  地址

原理是会在有.project文件的目录生成一个.jars文件用来记录 相对地址下的jar,及其md5值

最后发现:其实并没有什么用,权当呵呵了。

代码集

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * 模拟Maven管理jar包,程序。
 * 
 * @author zenglb
 */
public class Jars {
    /**
     * 池的根目录
     */
    private final File jarsCache;
    private final String jarsCachePath;
    /**
     * 默认提供的配置文件。
     */
    private static final String DEFAULT_JARS_FILE_NAME = "/.jars";
 
    /**
     * 需要传入jar池的地址。
     * 
     * @param jarsCache
     */
    public Jars(String jarsCache) {
        this.jarsCache = new File(jarsCache);
        if (!this.jarsCache.exists()) {
            this.jarsCache.mkdir();
        }
        if (this.jarsCache.isFile()) {
            throw new IllegalArgumentException("jarsCache must exists be a Directory!");
        }
        jarsCachePath = this.jarsCache.getAbsolutePath();
    }
 
    public Jars() {
        this("D:/0_base" + DEFAULT_JARS_FILE_NAME);
    }
 
    public void analysis(String pathName, boolean isCache, boolean isClear) {
        File path = new File(pathName);
        if (!path.exists() || path.isFile()) {
            throw new IllegalArgumentException("pathName must exists and isDirectory!");
        }
        fileEach(path, isCache, isClear);
    }
 
    private void fileEach(File path, boolean isCache, boolean isClear) {
        if (null != path) {
            Logs.debug("analysis isCache = [%s] isClear =[%s]  %s ", isCache, isClear, path.getAbsolutePath());
            if (path.exists()) {
                if (path.isFile()) {
                    return;
                }
                boolean project = isProject(path);
                if (project) {
                    if (isCache) {
                        cacheProject(path, isClear);
                    } else {
                        restoreProject(path);
                    }
                } else {
                    File[] files = path.listFiles();
                    if (null != files) {
                        for (File file : files) {
                            fileEach(file, isCache, isClear);
                        }
                    }
                }
            }
        }
    }
 
    /**
     * 还原一个java工程
     * 
     * @param path
     */
    private void restoreProject(File path) {
        if (isProject(path)) {
            String base = path.getAbsolutePath();
            Logs.debug("restore project: %s", base);
            Logs.debug("=======================================");
            File jars = new File(base + DEFAULT_JARS_FILE_NAME);
            if (jars.exists() && jars.isFile()) {
                BufferedReader in = null;
                try {
                    in = new BufferedReader(new FileReader(jars));
                    String line = null;
                    String[] tt = null;
                    File jar = null;
                    while (null != (line = in.readLine())) {
                        tt = line.split("####");
                        if (tt.length == 2) {
                            jar = new File(base + tt[0].trim());
                            Logs.debug("try restore %s >> %s", jar.getName(), tt[1].trim());
                            restoreJar(jar, tt[1].trim());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    IOKit.closeIo(in);
                }
 
            }
        }
    }
 
    /**
     * 缓存一个工程
     * 
     * @param path
     * @param isClear
     */
    private void cacheProject(File path, boolean isClear) {
        if (isProject(path)) {
            Logs.debug("cache project: %s", path.getAbsolutePath());
            Logs.debug("-----------------------------------------");
            List<File> jarFileLst = new ArrayList<File>();
            findJars(path, jarFileLst);
 
            String md5 = null;
            String relativePath = null;
            ArrayList<String> jarsContent = new ArrayList<String>();
            int basePath = path.getAbsolutePath().length();
            for (File jar : jarFileLst) {
                md5 = getFileMD5(jar);
                Logs.debug("try cache %s >> %s", jar.getName(), md5);
                relativePath = jar.getAbsolutePath().trim().substring(basePath);
                jarsContent.add(relativePath + "####" + md5);
                cacheJar(jar, md5);
            }
 
            if (!jarsContent.isEmpty()) {
                File f = new File(path.getAbsolutePath() + DEFAULT_JARS_FILE_NAME);
                if (f.exists()) {
                    Logs.debug("rename " + DEFAULT_JARS_FILE_NAME);
 
                    copyFile(f, new File(
                            f.getAbsoluteFile() + ".bak." + DateKit.printDateTime(new Date(), "yyyyMMddHHmmss")));
                }
                PrintWriter out = null;
                try {
                    out = new PrintWriter(f);
                    for (String ss : jarsContent) {
                        out.println(ss);
                    }
                } catch (FileNotFoundException e) {
                } finally {
                    try {
                        out.flush();
                    } catch (Exception e) {
                    }
                    IOKit.closeIo(out);
                }
                if (isClear) {
                    Logs.debug("delete jars! : %s", jarFileLst.size());
                    for (File file : jarFileLst) {
                        file.delete();
                    }
                }
            }
            Logs.debug("=======================================");
            Logs.debug("\n");
        }
    }
 
    /**
     * 查找工程中的所有jar包
     * 
     * @param path
     * @param jarFileLst
     */
    private void findJars(File path, List<File> jarFileLst) {
        if (null != jarFileLst && null != path && path.exists()) {
            if (path.isFile() && path.getName().trim().toLowerCase().endsWith(".jar")) {
                jarFileLst.add(path);
            } else if (path.isDirectory()) {
                File[] files = path.listFiles();
                if (null != files) {
                    for (File file : files) {
                        findJars(file, jarFileLst);
                    }
                }
            }
        }
    }
 
    /**
     * 缓存jar
     * 
     * @param jar
     * @param md5
     * @return
     */
    private boolean cacheJar(File jar, String md5) {
        if (null != jar && jar.isFile() && null != md5) {
            File saveFile = new File(jarsCachePath + getCachePath(jar.getName(), md5));
            FileKit.makeDir(saveFile.getParentFile());
            if (saveFile.exists() && md5.equals(getFileMD5(saveFile))) {// 已经存在
                Logs.debug("cache %s exists", jar.getName());
                return true;
            }
            copyFile(jar, saveFile);
            Logs.debug("cache  %s success", jar.getName());
            return true;
        }
        Logs.debug("cache  %s[%s] falid", null != jar ? jar.getName() : "ERR", md5);
        return false;
    }
 
    /**
     * 还原一个jar到指定地址
     * 
     * @param jar
     * @param md5
     * @return
     */
    private boolean restoreJar(File jar, String md5) {
        String name = jar.getName();
        if (jar.exists() && md5.equals(getFileMD5(jar))) {
            Logs.debug("restore %s exists", name);
            return true;
        }
        File dbFile = new File(jarsCachePath + getCachePath(name, md5));
        if (dbFile.exists() && md5.equals(getFileMD5(dbFile))) {
            FileKit.makeDir(jar.getParentFile());
            copyFile(dbFile, jar);
            Logs.debug("restore  %s success", name);
            return true;
        }
        Logs.debug("restore  %s[%s] falid", name, md5);
        return false;
    }
 
    /**
     * 通过名字的hash值计算包所在地址。
     * 
     * @param name
     * @param md5
     * @return
     */
    protected String getCachePath(String name, String md5) {
        int hash = name.hashCode();
        hash = (hash > 0 ? hash : 0 - hash) % 1000;
        return String.format("/%3$02x/%4$03x/%1$s_%2$s", name, md5, hash / 100, hash % 100);
    }
 
    /**
     * 是否为一个项目,包含.classpath和.project文件就是项目。
     * 
     * @param path
     * @return
     */
    public boolean isProject(File path) {
        int i = 1;
        if (null != path && path.exists() && path.isDirectory()) {
            File[] lst = path.listFiles();
            String fileName = null;
            if (null != lst) {
                for (File file : lst) {
                    if (file.isFile()) {
                        fileName = file.getName();
                        if (".project".equalsIgnoreCase(fileName.trim())) {
                            i--;
                        }
                    }
                }
            }
        }
        return i <= 0;
    }
 
    /**
     * 计算文件的MD5值
     * 
     * @param file
     * @return
     */
    private static String getFileMD5(File file) {
        if (null == file || !file.isFile()) {
            return null;
        }
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] data = IOKit.readToByteBuffer(in, Integer.MAX_VALUE);
            return DigestKit.md5Digest(data).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOKit.closeIo(in);
        }
        return null;
    }
 
    private static boolean copyFile(File src, File to) {
        if (null != src && src.isFile() && null != to) {
            FileInputStream in = null;
            FileOutputStream out = null;
            byte[] tmp = new byte[8192];
            try {
                in = new FileInputStream(src);
                out = new FileOutputStream(to);
                int n = 0;
                while (-1 < (n = in.read(tmp))) {
                    out.write(tmp, 0, n);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != out) {
                    try {
                        out.flush();
                    } catch (IOException e) {
                    }
                    IOKit.closeIo(out);
                }
                IOKit.closeIo(in);
            }
        }
        return false;
    }
 
    public static void main(String[] args) throws Exception {
        args = new String[] { "restore", "D:/tmp/J2EE_WP" };
        boolean isERROR = true;
        if (args.length >= 2) {
            Boolean isCache = null;
            boolean isClear = false;
            if ("cache".equals(args[0])) {
                isCache = true;
                if (args.length == 3) {
                    isClear = Boolean.valueOf(args[1]);
                }
            } else if ("restore".equals(args[0])) {
                isCache = false;
            }
            String pathName = args[args.length - 1].trim();
            if (null != isCache) {
                new Jars().analysis(pathName, isCache, isClear);
                return;
            }
        }
        if (isERROR) {
            Logs.debug("using type[cache|restore] isClear[true|false] projectPath");
        }
    }
}

创建目录

/**
 * 创建文件夹
 * 
 * @param file
 * @return
 */
public static synchronized boolean makeDir(File file) {
    if (null != file) {
        if (file.exists() && file.isDirectory()) {
            return true;
        }
        if (makeDir(file.getParentFile())) {
            file.mkdir();
            return true;
        }
    }
    return false;
}

读取数据

public static byte[] readToByteBuffer(InputStream inStream, int maxSize) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        if (maxSize > 0) {
            int bufferSize = 0x2000;
            byte[] buffer = new byte[bufferSize];
            int read;
            int remaining = maxSize;
 
            while (true) {
                read = inStream.read(buffer);
                if (-1 == read) {
                    break;
                }
                if (read > remaining) {
                    outStream.write(buffer, 0, remaining);
                    break;
                }
                remaining -= read;
                outStream.write(buffer, 0, read);
                if (bufferSize > read) {
                    break;
                }
            }
        }
        return outStream.size() > 0 ? outStream.toByteArray() : null;
    }

猜你喜欢

转载自my.oschina.net/u/727875/blog/1826090
今日推荐