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) + ""); } }
  • 相关阅读:
    《Redis 垃圾回收》
    python-Day3-set 集合-counter计数器-默认字典(defaultdict) -可命名元组(namedtuple)-有序字典(orderedDict)-双向队列(deque)--Queue单项队列--深浅拷贝---函数参数
    Python--day4
    python--day2
    Python--day1
    Python字符串原理剖析------万恶的+号
    执行脚本传入参数
    字符编码
    css3动画与js动画的区别
    关于FormData及其用法
  • 原文地址:https://www.cnblogs.com/proli/p/8303350.html
Copyright © 2011-2022 走看看