jar 包内文件的遍历以及文件的拷贝

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

public class Main1
{
    
    /**
     * jar
     * 
     * @param args
     * @see [类、类#方法、类#成员]
     */
    public static void main(String[] args)
    {
        String dir = "D:\\classes\\";
        new File(dir).mkdirs();
        // 如果StringUtils类在jar内,返回jar物理路径
        URL url = StringUtils.class.getProtectionDomain().getCodeSource().getLocation();
        if (url.getPath().endsWith(".jar"))
        {
            try
            {
                JarFile jarFile = new JarFile(url.getFile());
                Enumeration<JarEntry> entrys = jarFile.entries();
                while (entrys.hasMoreElements())
                {
                    JarEntry jar = entrys.nextElement();
                    String name = jar.getName();
                    if (name.endsWith(".class"))
                    {
                        System.out.println(name);
                        // jar内的文件只能通过流处理
                        InputStream in = StringUtils.class.getClassLoader().getResourceAsStream(name);
                        File parent = new File(dir + name).getParentFile();
                        if (!parent.exists())
                        {
                            parent.mkdirs();
                        }
                        OutputStream out = new FileOutputStream(dir + name);
                        IOUtils.copy(in, out);
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                }
                jarFile.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16127313/article/details/82920560