1、最近作項目的時候,師兄要求讀取jar包裏面的java文件。在網上查了各類文件之後,終於完成了,在這裏和各位朋友分享一下。java
(一)找到jar包所在的位置。app
(二)找到jar包所在的位置之後,經過JarFile這個類讀取文檔中的內容,得到全部的文件夾名字url
JarFile jarFile = new JarFile(new File(filePath)); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName();
//讀取文件後綴名爲.java的文件 if (!entry.isDirectory() && entryName.endsWith(".java")) { 讀取操做。。。。。。 } }
3、獲取jar包文件裏面的文件IO流spa
//filePath是jar文件位置,name是jar文件裏面文件的路徑,至關於上面代碼框中的entryName
public InputStream getJarInputStream(String filePath, String name) throws Exception { URL url = new URL("jar:file:" + filePath + "!/" + name); JarURLConnection jarConnection = (JarURLConnection) url .openConnection(); InputStream in = jarConnection.getInputStream(); return in; }
4、讀取文件code
public String readFile(String filePath, String entryName, Integer index) { InputStream in = null; BufferedReader br = null; StringBuffer sb = null; try { in = getJarInputStream(filePath, entryName); br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String con = null; sb = new StringBuffer(); while ((con = br.readLine()) != null) { if (before <= row && row < after) { sb.append(con); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
注意:關閉IO流,在工做中是甲級錯誤blog