1. 程式人生 > >程式碼生成MANIFEST.MF檔案

程式碼生成MANIFEST.MF檔案

我在查詢怎麼把java專案打包成jar包時,很多文章都提到了MANIFEST.MF這個檔案,但是對於怎麼生成這個檔案,都只是說了手寫,手寫,手寫。真好意思啊。

於是我就寫了一個簡易版的自動生成程式碼,只生成了比較關鍵的部分。

lib資訊取自.classpath檔案,如果由於ide的原因沒有這個檔案或者格式不一樣,本文方法不適用(我用的是myeclipse)。

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.
io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { /** * @param args * @throws IOException */ public
static void main(String[] args) throws IOException { // TODO Auto-generated method stub String mainClass = Test.class.getName(); //要啟動的類 System.out.println(new File(".classpath").exists()); List<String> list = readFile(".classpath"); Pattern pattern = Pattern.compile("path=\"(.*?)\""
); Pattern patternCheck = Pattern.compile("kind=\"lib\""); Matcher matcher; String libStr = ""; for(String str : list){ matcher = patternCheck.matcher(str); if(!matcher.find()) continue; matcher = pattern.matcher(str); if(matcher.find()) libStr += matcher.group(1) + " "; } if(libStr == null || libStr.length() == 0) libStr += " "; File file = new File("MANIFEST.MF"); file.delete(); file.createNewFile(); writeTxtFile(file, "Manifest-Version: 1.0"); writeTxtFile(file, "Main-Class: " + mainClass); writeTxtFile(file, "Class-Path: " + libStr); } public static List<String> readFile(String path) throws IOException { List<String> list = new ArrayList<String>(); FileInputStream fis = new FileInputStream(path); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); String line = ""; while ((line = br.readLine()) != null) { if (line.lastIndexOf("---") < 0) { list.add(line); } } br.close(); isr.close(); fis.close(); return list; } public static boolean writeTxtFile(File file, String newStr) throws IOException { boolean flag = false; String filein = newStr + "\r\n"; String temp = ""; FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; FileOutputStream fos = null; PrintWriter pw = null; try { fis = new FileInputStream(file); isr = new InputStreamReader(fis); br = new BufferedReader(isr); StringBuffer buf = new StringBuffer(); for (int j = 1; (temp = br.readLine()) != null; j++) { buf = buf.append(temp); buf = buf.append(System.getProperty("line.separator")); } buf.append(filein); fos = new FileOutputStream(file); pw = new PrintWriter(fos); pw.write(buf.toString().toCharArray()); pw.flush(); flag = true; } catch (IOException e) { throw e; } finally { if (pw != null) { pw.close(); } if (fos != null) { fos.close(); } if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } } return flag; } }