从jar包中读取文件的几种方式

写在前面

本文会用到这篇文章。

1:从自身读取文件

1.1:定义读取的文件

从jar包中读取文件的几种方式_第1张图片

1.2:读取代码

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws URISyntaxException, IOException {
        // fileName是在当前类路径中的一个文件
        InputStream in = HelloWorldMainApplication.class.getResourceAsStream("../../myfile.txt");
        if (null != in) {
            File file = new File("D:\\test\\myfile.txt");
            file.delete();
            file.createNewFile();
            OutputStream out = new FileOutputStream(file);
            byte[] bytes = new byte[1];
            while (in.read(bytes) != -1) {
                out.write(bytes);
            }
            out.flush();
        }
        SpringApplication.run(HelloWorldMainApplication.class, args);
        System.exit(0);
    }

}

1.3:package打jar

参考这篇文章。

1.4:运行

从jar包中读取文件的几种方式_第2张图片

1.5:查看生成文件

从jar包中读取文件的几种方式_第3张图片

2:获取当前jar所在的路径

2.1:测试代码

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws URISyntaxException, IOException {
        String path;
        URL url = HelloWorldMainApplication.class.getProtectionDomain().getCodeSource().getLocation();
        URLConnection connection = url.openConnection();
        if(connection instanceof JarURLConnection) {
            JarFile jarFile = ((JarURLConnection) connection).getJarFile();
            path = jarFile.getName();
            int separator = path.indexOf("!/");
            if (separator > 0) {
                path = path.substring(0, separator);
            }
        } else {
            path = url.getPath();
        }
        System.out.println("当前jar物理路径是:" + path);

        SpringApplication.run(HelloWorldMainApplication.class, args);
        System.exit(0);
    }

}

2.2:package打jar

参考这篇文章。

2.3:运行

从jar包中读取文件的几种方式_第4张图片

3:获取其他jar中的文件

3.1:测试的jar

从jar包中读取文件的几种方式_第5张图片
自己随便找一个jar就可以进行后续测试,这里只是贴下我使用的jar,方便和输出做对比。

3.2:测试程序

public static void main(String[] args) throws Exception {
    JarFile jarFile = new JarFile("d:\\test\\cglib-2.1.95.jar");
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        InputStream inputStream = jarFile.getInputStream(jarEntry);
        System.out.println("名称:" + jarEntry.getName() + " ,流对象: " + inputStream + ",大小:" + inputStream.available());
    }
}

运行结果:

名称:META-INF/ ,流对象: java.util.zip.ZipFile$ZipFileInputStream@372f7a8d,大小:0
名称:META-INF/MANIFEST.MF ,流对象: java.util.zip.ZipFile$ZipFileInflaterInputStream@2f92e0f4,大小:1401
...snip...
名称:META-INF/maven/org.glassfish.hk2.external/cglib/ ,流对象: java.util.zip.ZipFile$ZipFileInputStream@452b3a41,大小:0
名称:LICENSE ,流对象: java.util.zip.ZipFile$ZipFileInflaterInputStream@4a574795,大小:11357
名称:net/sf/cglib/util/ParallelSorter$IntComparer.class ,流对象: java.util.zip.ZipFile$ZipFileInflaterInputStream@f6f4d33,大小:648
...snip...
名称:net/sf/cglib/util/ParallelSorter.class ,流对象: java.util.zip.ZipFile$ZipFileInflaterInputStream@65b54208,大小:4269

4:通用方式(建议这种!!!)

假设在classpath有如下的文件:
在这里插入图片描述
通过如下的代码,不管是直接运行,还是可执行jar包运行都可以读取到:

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = HelloWorldMainApplication.class.getClassLoader();
        URL resource = classLoader.getResource("aaa/bb/dddd.txt");
        System.out.println("路径是:" + resource.getPath());
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), "utf-8"));
        String line;
        String result = "";
        while ((line = reader.readLine()) != null) {
            result += line;
        }
        System.out.println("内容是:" + result);
        SpringApplication.run(HelloWorldMainApplication.class, args);
    }
}

如下是我本地直接运行和可执行jar运行的结果:
从jar包中读取文件的几种方式_第6张图片在这里插入图片描述
也可以从其他jar中读取文件,比如读取如下的文件:
从jar包中读取文件的几种方式_第7张图片
程序如下:

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = HelloWorldMainApplication.class.getClassLoader();
//        URL resource = classLoader.getResource("aaa/bb/dddd.txt");
        URL resource = classLoader.getResource("META-INF/spring.factories");
        System.out.println("路径是:" + resource.getPath());
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), "utf-8"));
        String line;
        String result = "";
        while ((line = reader.readLine()) != null) {
            result += line;
        }
        System.out.println("内容是:" + result);


        SpringApplication.run(HelloWorldMainApplication.class, args);
    }
}

朋友们自己试下。如果是在本地的resource下也有META-INF/spring.factories,如下图:
从jar包中读取文件的几种方式_第8张图片
也可以通过如下代码同时读取多个:

@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = HelloWorldMainApplication.class.getClassLoader();
//        URL resource = classLoader.getResource("aaa/bb/dddd.txt");
        Enumeration<URL> resources = classLoader.getResources("META-INF/spring.factories");
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            System.out.println("路径是:" + resource.getPath());
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), "utf-8"));
            String line;
            String result = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            System.out.println("内容是:" + result);
        }

        SpringApplication.run(HelloWorldMainApplication.class, args);
    }
}

输出如下:
在这里插入图片描述

你可能感兴趣的:(杂,java,jar)