jar包的讀取1
阿新 • • 發佈:2018-06-01
初始化 num 形式 append bis clas 目錄 訪問 ringbuf
---恢復內容開始---
昨天在做項目插件的時候,因為會用到jar包中的一個文件來初始化程序。並且以後還是會訪問這個文件,所以就想到幹脆吧文件拷貝到指定目錄。在拷貝的時候也費了好一會時間,這裏涉及到了jar文件的操作,在這裏記下來以後有用到的時候方便查找
- 如果jar中還存在jar包或者其他壓縮包,則使用這種方式讀取
-
1 public class JarFileAccess { 2 3 private static final String fileSeparator = System.getProperty("file.separator"); 4 /** 5 *
-
- 如果要讀取的文件在jar包中不是以壓縮包或jar的形式存在,用下面的方式方便點
-
1 public class JarFileAccess{ 2 /** 3 * @function 讀取jar包中指定文件的內容並且以字符串形式返回 4 * @param jarPath jar文件的路徑 5 * @param name 要讀取的文件名稱,要添加後綴名 6 * @return String 返回讀取到的信息 7 * @throws IOException 8 */ 9 public String readFileFromJar(String jarPath ,String name) throws IOException { 10 JarFile jf = new JarFile(jarPath); 11 Enumeration<JarEntry> jfs = jf.entries(); 12 StringBuffer sb = new StringBuffer(); 13 while(jfs.hasMoreElements()) 14 { 15 JarEntry jfn = jfs.nextElement(); 16 if(jfn.getName().endsWith(name)) 17 { 18 InputStream is = jf.getInputStream(jfn); 19 BufferedInputStream bis = new BufferedInputStream(is); 20 byte[] buf = new byte[is.available()]; 21 while(bis.read(buf)!=-1) 22 { 23 sb.append(new String(buf).trim()); 24 } 25 bis.close(); 26 is.close(); 27 break; 28 } 29 } 30 return sb.toString(); 31 } 32 /** 33 * @function 讀取jar包中指定文件的內容並且將讀取到的內容拷貝到指定文件中 34 * @param jarPath jar文件的路徑 35 * @param name 要讀取的文件名稱,要添加後綴名 36 * @param toNewFile 將拷貝到的信息復制到目標文件 37 * @throws IOException 38 */ 39 public void readFileFromJar(String jarPath ,String name,File toNewFile) throws IOException { 40 JarFile jf = new JarFile(jarPath); 41 Enumeration<JarEntry> jfs = jf.entries(); 42 StringBuffer sb = new StringBuffer(); 43 while(jfs.hasMoreElements()) 44 { 45 JarEntry jfn = jfs.nextElement(); 46 if(jfn.getName().endsWith(name)) 47 { 48 InputStream is = jf.getInputStream(jfn); 49 FileOutputStream fos = new FileOutputStream(toNewFile); 50 BufferedInputStream bis = new BufferedInputStream(is); 51 byte[] buf = new byte[is.available()]; 52 while(bis.read(buf)!=-1) 53 { 54 fos.write(buf); 55 56 } 57 fos.close(); 58 bis.close(); 59 is.close(); 60 break; 61 } 62 } 63 64 } 65 66 }
-
---恢復內容結束---
jar包的讀取1