zoukankan      html  css  js  c++  java
  • 工程打成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) + ""); } }
  • 相关阅读:
    Mybatis Generator生成Mybatis Dao接口层*Mapper.xml以及对应实体类
    ssh通过pem文件登陆服务器
    maven私服nexus上传第三方jar包以及下载
    springboot不占用端口启动
    springboot2.x纯注解整合dubbo
    mysql5.7 group by语法 1055
    java读取pdf文本转换html
    java 记录对象前后修改的内容(工具类)
    在docker中运行mysql实例
    Linux编辑启动停止重启springboot jar包脚本
  • 原文地址:https://www.cnblogs.com/proli/p/8303350.html
Copyright © 2011-2022 走看看