JAR文件本质上是一种ZIP格式的文件,有些时候java程序需要访问JAR包中的某资源文件(例如properties文件),但此时是不能使用File类来操作的,这是因为File类是不能访问压缩包内的文件路径的。一种办法是利用java.util.zip 或者java.util.jar 包中的API操作JAR包,但是代码写起来比较麻烦;还有一种更简单的方法是利用Class类的getResourceAsStream(String name)方法来访问jar包内的资源。一个简单的示例如下:

package cn.edu.ustb.math;

import java.io.*;

public class AccessJar{
   public void backupResourceFile(String resourceName) throws IOException{
     //load resource as bytes
    InputStream is = getClass().getResourceAsStream(resourceName);
     //The InputStream instance will be different for folder path and jar file path
     System.out.println(is.getClass().getName());
     //backup resource
     OutputStream fos = new FileOutputStream((resourceName.startsWith("/")?
               resourceName.substring(1):resourceName)+".bak");
     byte[] buf = new byte[1024];
     int i;
     while((i=is.read(buf))!=-1){
      fos.write(buf, 0, i); 
     }
     fos.close();
   }

   public static void main(String[] args){
    try{
     new AccessJar().backupResourceFile("/fr-019-v110.exe"); 
     /**
      If the file name begins with a '/' ('\u002f'), then the absolute name of 
      the resource is the portion of the name following the '/'. 
         Otherwise, the absolute name is of the following form: 
             modified_package_name/name
          Where the modified_package_name is the package name of this object 
          with '/' substituted for '.' ('\u002e'). 
     */
     System.out.println("Done!");
    } 
    catch(IOException e){
     e.printStackTrace(); 
    }
   }
}