从jar包中读取文件
以下的Java代码实现了从一个jar包中读取指定文件的功能:
1/**
2 * This class implements the funcationality of reading and writing files in jar files.
3 */
4package com.leo.util;
5
6import java.io.InputStream;
7import java.io.FileOutputStream;
8import java.util.jar.*;
9import java.util.Enumeration;
10
11/**
12 * @author Leo Share
13 * @since 08/09/2007
14 * @version 1.0
15 */
16
17public class JarFileAccess {
18 private static final String fileSeparator = System.getProperty("file.separator");
19
20 public void accessJarFile(String jarFileName, String fromDir, String toDir) throws Exception{
21 JarFile myJarFile = new JarFile(fromDir+fileSeparator+jarFileName);
22 Enumeration myEnum = myJarFile.entries();
23 while(myEnum.hasMoreElements()){
24 JarEntry myJarEntry = (JarEntry)myEnum.nextElement();
25 if(myJarEntry.getName().equals("jbossall-client.jar")){
26 InputStream is = myJarFile.getInputStream(myJarEntry);
27 FileOutputStream fos = new FileOutputStream(toDir+fileSeparator+myJarEntry.getName());
28 byte[] b = new byte[1024];
29 int len;
30 while((len = is.read(b))!= -1){
31 fos.write(b, 0, len);
32 }
33 fos.close();
34 is.close();
35 break;
36 }
37 else{
38 continue;
39 }
40 }
41 myJarFile.close();
42 }
43}
2 * This class implements the funcationality of reading and writing files in jar files.
3 */
4package com.leo.util;
5
6import java.io.InputStream;
7import java.io.FileOutputStream;
8import java.util.jar.*;
9import java.util.Enumeration;
10
11/**
12 * @author Leo Share
13 * @since 08/09/2007
14 * @version 1.0
15 */
16
17public class JarFileAccess {
18 private static final String fileSeparator = System.getProperty("file.separator");
19
20 public void accessJarFile(String jarFileName, String fromDir, String toDir) throws Exception{
21 JarFile myJarFile = new JarFile(fromDir+fileSeparator+jarFileName);
22 Enumeration myEnum = myJarFile.entries();
23 while(myEnum.hasMoreElements()){
24 JarEntry myJarEntry = (JarEntry)myEnum.nextElement();
25 if(myJarEntry.getName().equals("jbossall-client.jar")){
26 InputStream is = myJarFile.getInputStream(myJarEntry);
27 FileOutputStream fos = new FileOutputStream(toDir+fileSeparator+myJarEntry.getName());
28 byte[] b = new byte[1024];
29 int len;
30 while((len = is.read(b))!= -1){
31 fos.write(b, 0, len);
32 }
33 fos.close();
34 is.close();
35 break;
36 }
37 else{
38 continue;
39 }
40 }
41 myJarFile.close();
42 }
43}