How to add resources to classpath

ε祈祈猫儿з 提交于 2019-11-27 11:58:45
Tushar Joshi
  1. Adding resource folder to classpath:

    When you Clean-&-Build a NetBeans Ant Based Project it creates a manifest.mf file in the root directory of the project. This file gets included in the JAR file also. Modify this file and add entry like follows:

    Manifest-Version: 1.0
    X-COMMENT: Main-Class will be added automatically by build
    Class-Path: arts/  
    

    slash is important after arts in the class path.

  2. Including the arts resource folder in the distribution

    Either copy this folder in the dist folder after the build or add a ANT target to copy the required resources in the dist folder.

    Add the target like as follows in the build.xml file:

    <target name="-post-jar">
         <mkdir dir="${dist.dir}/resources"/>
         <copy todir="${dist.dir}/resources">
             <fileset dir="${basedir}/resources" />
         </copy>
     </target>
    
  3. Code to access such resources:

    The code needed to access such resource files shall be as follows: (This will not work in design time but surely from the JAR file)

    // pay attention to relative path
    URL resource = ClassLoader.getSystemResource("gui/refresh.png"); 
    ImageIcon tmp = new ImageIcon(resource);
    

    NOTE: The files manifest.mf and build.xml located in the root directory of the project are accessible from the Files Panel in NetBeans IDE

Squiggler

Using NetBeans 8.0.2:

  1. Right-click the project.
  2. Select Properties.
  3. Select Sources.
  4. Click Add Folder for the Source Package Folders.
  5. Select the the directory where the resources exist.
  6. Click Open on the directory name.
  7. Click OK to close the Project Properties dialog.

The resources are added to the project.

You'll see the directory added in your Navigation pane as well

In the other project, the resources are now available. For example, to read an image:

BufferedImage zero = ImageIO.read(OCR.class.getResourceAsStream("/0.bmp"));

In order to remove the lib/art from Class-Path and not get "is a directory or can't be read" need delete lib/art from path:

    <pathconvert property="run.classpath.without.build.classes.dir">
      <path path="${run.classpath}"/>
      <map from="${build.classes.dir.resolved}" to=""/>
      **<map from="${basedir}/art" to=""/> <!-- remove art from lib -->**
    </pathconvert>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!