簡體   English   中英

使用python zipfile命令將類文件替換/添加到jar中的子文件夾

[英]Replace/Add a class file to subfolder in jar using python zipfile command

我有一個jar文件,並且有一個路徑代表了Jar文件中的位置。

使用這個位置,我需要替換jar文件中的類文件(在某些情況下添加類文件)。我在存在jar的另一個文件夾中有類文件(我必須將該類文件移動到Jar中)。

我正在嘗試實現上述目標的代碼:

 import zipfile
 import os

 zf = zipfile.ZipFile(os.path.normpath('D:\mystuff\test.jar'),mode='a')
 try:
     print('adding testclass.class')
     zf.write(os.path.normpath('D:\mystuff\testclass.class'))
 finally:
     print('closing')
     zf.close()

執行完上面的代碼后,當我看到下面提到的格式的jar時:

  Jar
   |----META-INF
   |----com.XYZ
   |----Mystuff
          |--testclass.class

我需要的實際輸出是-

   Jar
    |----META-INF
    |----com.XYZ
           |--ABC
               |-testclass.class

如何使用zipfile.write命令或python中的任何其他方式實現此目的?

我沒有在write命令中找到任何可以在Jar / Zip文件中提供目標文件位置的參數。

ZipFile.write(文件名,弧名=無,compress_type =無)

指定arcname可以更改存檔中文件的名稱。

import zipfile
import os

 zf = zipfile.ZipFile(os.path.normpath(r'D:\mystuff\test.jar'),mode='a')
 try:
     print('adding testclass.class')
     zf.write(os.path.normpath(r'D:\mystuff\testclass.class'),arcname="com.XYZ/ABC/testclass.class")
 finally:
     print('closing')
     zf.close()

注意:我懷疑test.jar是您的真實jar名稱,因為您沒有保護字符串不受特殊字符的影響,並且打開的jar文件將是'D:\\mystuff\\<TAB>est.jar' (嗯,它沒有不工作:))

編輯:如果您想添加新文件但刪除舊文件,則必須做不同的事情:您無法從zip 文件中刪除 ,而必須重建另一個文件 (受ZipFile Module從zipfile中刪除文件的啟發)

import zipfile
import os

infile = os.path.normpath(r'D:\mystuff\test.jar')
outfile = os.path.normpath(r'D:\mystuff\test_new.jar')

zin = zipfile.ZipFile(infile,mode='r')
zout = zipfile.ZipFile(outfile,mode='w')
for item in zin.infolist():
    if os.path.basename(item.filename)=="testclass.class":
        pass  # skip item
    else:
        # write the item to the new archive
        buffer = zin.read(item.filename)
        zout.writestr(item, buffer)

print('adding testclass.class')
zout.write(os.path.normpath(r'D:\mystuff\testclass.class'),arcname="com.XYZ/ABC/testclass.class")

zout.close()
zin.close()

os.remove(infile)
os.rename(outfile,infile)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM