工程打成jar后,jar包自己读取不到文件夹中的资源

项目中需要读取文件夹中的所有图片,在工程中能成功读取

打成Jar包后,使用jar包,自己就读取不到 

当打成一个jar包后,整个jar包是一个文件,只能使用流的方式读取资源,这时候就不能通过File来操作资源了,得通过getResourceAsStream来读取文件内容并操作

在IDE中之所以能正常运行,是因为IDE中的资源文件在target/classes目录下,是正常的文件系统结构。

----

之前使用File 来取,工程中运行没问题,打成Jar包后就,读取不到一直为null

File dir = new File(dirPath + "train");
File[] files = dir.listFiles();
for (File file : files)
{
 map.put(ImageIO.read(file), file.getName().charAt(0) + "");
}

网上查找资料后,打成Jar包后顺利读取资源子文件夹中所有文件:

private static final String fileName = "com/xxx/xxx/xxx/ocrTrain/train";

private static final URL dirPath = CIRCAndTPOcrUtil.class.getClassLoader().getResource(fileName);
       
       String jarPath = dirPath.toString().substring(0, dirPath.toString().indexOf("!/") + 2); URL jarURL = new URL(jarPath); JarURLConnection jarURLConnection = (JarURLConnection) jarURL.openConnection(); JarFile jarFile = jarURLConnection.getJarFile(); Enumeration<JarEntry> jarEntrys = jarFile.entries(); while (jarEntrys.hasMoreElements()) { JarEntry entry = jarEntrys.nextElement(); String name = entry.getName(); if (name.startsWith(fileName) && !entry.isDirectory()) {
            //读取到文件夹下的所有图片 map.put(ImageIO.read(CIRCAndTPOcrUtil.
class.getClassLoader().getResourceAsStream(name)) , name.substring(name.lastIndexOf("/") + 1).charAt(0) + ""); } }
原文地址:https://www.cnblogs.com/proli/p/8303350.html