jar包不用java命令_使不能运行的JAR文件可以使用java -jar运行
"); System.exit(0); }
請注重參數列表是如何被解釋的,因為這對于后面的代碼是非常重要的。參數的順序和內容并不是硬性設置的,但是假如你改變它們也要記得適當的修改其他的代碼。
訪問JAR和它的manifest文件
首先我們必須創建一些知道JAR和manifest文件的對象:
//Create the JarInputStream object, and get its manifest JarInputStream jarIn = new JarInputStream(new FileInputStream(args[0])); Manifest manifest = jarIn.getManifest(); if (manifest == null) { //This will happen if no manifest exists manifest = new Manifest(); }
設置Main-Class屬性
我們將Main-Class條目放到manifest文件的主要屬性部分。一旦我們從manifest對象獲得了這個屬性集我們就可以設置適當的主類。然而假如一個Main-Class屬性已經存在于原來的JAR時怎么辦?這個程序簡單的打印一個警告并退出?;蛟S我們可以增加一個命令行參數告訴程序用新的值替換已經存在的那個值.
Attributes a = manifest.getMainAttributes(); String oldMainClass = a.putValue("Main-Class", args[1]); //If an old value exists, tell the user and exit if (oldMainClass != null) { System.out.println("Warning: old Main-Class value is: " + oldMainClass); System.exit(1); }
輸出新的JAR
我們需要創建一個新的jar文件,因為我們必須使用JarOutputStream類。注重我們必須保證沒有將輸入作為輸出使用。作為替代,也許程序應該考慮兩個jar文件相同并且提示用戶是否覆蓋原來的。然而我將這個保留給讀者作為練習。
System.out.println("Writing to " + args[2] + "..."); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(args[2]), manifest);
我們必須將原來的JAR中的每個條目都寫到新的JAR中,因為對那些條目迭代:
//Create a read buffer to transfer data from the input byte[] buf = new byte[4096]; //Iterate the entries JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { //Exclude the manifest file from the old JAR if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; //Write the entry to the output JAR jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } //Flush and close all the streams jarOut.flush(); jarOut.close(); jarIn.close();
完整程序
當然我們必須將這些代碼放到一個類里面的main方法里面,并且具有合適的import聲明。
使用范例
讓我們用一個范例來使用這個程序。假設你有一個應用其main入口點是類HelloRunnableWorld(這個是它的全類名,也就是包含包名),同樣假設你已經創建了一個名字為myjar.jar的JAR,包含整個應用。對于這個jar,我們像這樣運行MakeJarRunnable:
java MakeJarRunnable myjar.jar HelloRunnableWorld myjar_r.jar
再強調一次,就像早先提到的,注重參數列表的順序。假如忘記了順序,以無參的形式運行程序它就會告訴你使用信息。
使用java -jar命令運行myjar.jar和myjar_r.jar,注重它們的差異。完成這些之后,查看一下它們的manifest文件(META-INF/MANIFEST.MF)。
這里有一個建議:將MakeJarRunnable制作成一個可以運行的JAR!
運行它
通過雙擊一個JAR或者使用簡單的命令總是比將它包含在你的classpath并運行特定的main類方便。為了幫助你作到這一點,JAR規范為JAR的manifest文件提供了一個Main-Class屬性。我在這里提出的這個程序讓你利用Java的JAR API非常輕易的操作這個屬性并制作你自己的可運行的JAR。
(#)
總結
以上是生活随笔為你收集整理的jar包不用java命令_使不能运行的JAR文件可以使用java -jar运行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 限制并发数_限制并发请求数ai
- 下一篇: java字符串学习_java之字符串学习