JAR EAR讀寫操作簡單例項

2021-08-24 19:01:21 字數 2023 閱讀 7264

1. 讀取jar包裡的manifest.mf檔案(讀取ear包裡的檔案相同的操作),大概步驟如下:

1)用jar包的絕對路徑作為構參,new乙個jarfile類

2)用jar包裡的乙個檔案檔案的相對路徑作為引數,呼叫jarfile類的乙個getjarentry的方法,得到乙個jarentry類

3)再用這個entry類作為引數,呼叫jarfile的getinputstream文法,得到這個檔案的inputstream

4)接下來對inputsteam的操作與普通讀取檔案的方法相同

stringbuffer sb = new stringbuffer();

trysystem.out.println(sb.tostring());

}catch (ioexception e)

2. 輸出ear包裡的jar到其它目錄,與從jar包讀取相似,操作步驟如下

1)用ear包的絕對路徑作為構參,new乙個jarfile類

2)用目標jar包的相對路徑作為引數,呼叫jarfile的getjarentry方法,得到乙個jarentry類

3)用這個jarentry作為引數,呼叫jarfile的getinputstream方法,取得這個jar包檔案的inputstream

4)接下來對inputstream的操作與普通寫檔案操作相同

try

fileoutputstream.flush();

fileoutputstream.close();

}catch (ioexception e)

3. 替換ear包裡的某些jar包, 相對之前幾個例項,這個會相對複雜一些,步驟如下:

1)建立乙個目標的ear包file類,然後再得到乙個jaroutputstream,接下來會往這裡新增需要的jar包

2)讀取源ear包,然後jarfile類的entries()方法遍歷源ear包的所有檔案

3)判斷要替換的jar檔案,跳過它,其它的檔案馬上寫入目標的ear包裡

4)關閉源ear包

5)建立要替換進來的jar包的jarentry,用fileinputstream類讀取這個jar包,然後馬上寫進目標ear包裡

6)flush jaroutputstream

7)依次關閉其它仍未關閉的資源

try

//其它檔案馬上寫到目標ear包裡去

inputstream jarinputstream = sourceearfile.getinputstream(jarentry);

newjaroutputstream.putnextentry(jarentry);

while ((bytesread = jarinputstream.read(buffer)) != -1)

newjaroutputstream.flush();

jarinputstream.close();

}//到這裡源ear包己經沒有用了,close掉

sourceearfile.close();

jarentry targetjarentry = new jarentry("targetjar.jar");

newjaroutputstream.putnextentry(targetjarentry);

fileinputstream targetjarfileinputstream = new fileinputstream("c:/test/targetjar.jar");

while ((bytesread = targetjarfileinputstream.read(buffer)) != -1)

newjaroutputstream.flush();

targetjarfileinputstream.close();

newjaroutputstream.close();

targetearfileoutputstream.close();

}catch (exception ex)

Python 檔案讀寫操作例項詳解

一 python中對檔案 資料夾操作時經常用到的os模組和shutil模組常用方法。1.得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 2.返回指定目錄下的所有檔案和目錄名 os.listdir 3.函式用來刪除乙個檔案 os.remove 4.刪除多個目錄 os.re...

Python 檔案讀寫基礎操作例項

本文針對python入門者提供了乙個檔案讀寫的例項,並且對程式進行了詳細的分析,保證剛接觸到python的入門者能理解。如下 created on aug 3 2007 author suqi791776 def main infile open test1.txt r test1 is a def...

csv 簡單的讀寫操作

csv的寫 python自帶了csv模組提供使用者對csv檔案進行寫操作,首先要建立乙個writer物件 import csv header a b c d rows 1 2 3 4 5 6 7 8 9 10 11 12 with open test.csv w as f f csv.writer ...