java 從jar中讀取檔案 三種方法
阿新 • • 發佈:2019-02-06
- Sample1-利用Manifest檔案讀取jar中的檔案
1.檔案目錄
test--
--a.text
--b.gif
2. Menifest檔案內容:
Manifest-Version: 1.0
abc: test/a.txt
iconname: test/Anya.jpg
注意:manifest.mf檔案最後一行要打一回車
Another Notification:
如果manifest檔案內容是:
Manifest-Version: 1.0
Main-Class: com.DesignToolApp
Class-path: lib/client.jar lib/j2ee.jar
在MANIFEST.MF檔案的最後,要留兩個空行(也就是回車),才可以識別到Class-Path這一行,如果只有一個空行,那麼只識別到Main- Class這一行。Class-Path中的庫名用空格格開,使用和jar包相對的路徑,釋出時把jar包和其他用到的類庫一起交給使用者就可以了。
3.打jar包
test.jar
![收藏程式碼](http://dcriori.iteye.com/images/icon_star.png)
- String iconpath = jar.getManifest().getMainAttributes().getValue("abc");
- InputStream in = jar.getInputStream(jar.getJarEntry(iconpath));
- //Image img = ImageIO.read(in);
- InputStreamReader isr = new InputStreamReader(in);
-
BufferedReader reader = new BufferedReader(isr);
- String line;
- while ((line = reader.readLine()) != null) {
- System.out.println(line);
- }
- reader.close();
- Sample2,讀取JAR 檔案列表及各項的名稱、大小和壓縮後的大小
![收藏程式碼](http://dcriori.iteye.com/images/icon_star.png)
- public class JarFileInfoRead {
- public static void main (String args[]) throws IOException {
-
String jarpath="d://temp//test.jar"
- JarFile jarFile = new JarFile(jarpath);
- Enumeration enu = jarFile.entries();
- while (enu.hasMoreElements()) {
- process(enu.nextElement());
- }
- }
- private static void process(Object obj) {
- JarEntry entry = (JarEntry)obj;
- String name = entry.getName();
- long size = entry.getSize();
- long compressedSize = entry.getCompressedSize();
- System.out.println(name + "\t" + size + "\t" + compressedSize);
- }
- }
- Sample3,讀取JAR中 檔案的內容
![收藏程式碼](http://dcriori.iteye.com/images/icon_star.png)
- public class JarFileRead {
- public static void main (String args[])
- throws IOException {
- String jarpath="d://temp//test.jar";
- JarFile jarFile = new JarFile(jarpath);
- Enumeration enu = jarFile.entries();
- while (enu.hasMoreElements()) {
- JarEntry entry = (JarEntry)enu.nextElement();
- String name = entry.getName();
- //System.out.println(name);
- if(name.equals("test/a.txt")){
- InputStream input = jarFile.getInputStream(entry);
- process(input);
- }
- }
- jarFile.close();
- }
- private static void process(InputStream input)
- throws IOException {
- InputStreamReader isr =
- new InputStreamReader(input);
- BufferedReader reader = new BufferedReader(isr);
- String line;
- while ((line = reader.readLine()) != null) {
- System.out.println(line);
- }
- reader.close();
- }
- }