0

I have a jar file and I have a path which represents a location inside Jar file.

Using this location I need to replace class file inside jar(Add a class file in some cases).I have class file inside another folder which is present where jar is present(This class file i have to move to Jar).

Code which I am trying to achieve above objective :

 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()

After executing above code when I saw jar below mentioned format:

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

Actual Output I need is -

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

How can achieve this using zipfile.write command or any other way in python?

I didn't find any params in write command where i can provide destination file location inside Jar/Zip file.

ZipFile.write(filename, arcname=None, compress_type=None)

Manjunath
  • 23
  • 6

1 Answers1

0

Specify arcname to change the name of the file in the archive.

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()

Note: I doubt test.jar is your real jar name, since you didn't protect your string against special chars and the jar file opened would have been 'D:\mystuff\<TAB>est.jar' (well, it doesn't work :))

EDIT: if you want to add the new file but remove the old one, you have to do differently: you cannot delete from a zipfile, you have to rebuild another one (inspired by Delete file from zipfile with the ZipFile Module)

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)
Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • But old file is not replaced. Is there any way to remove a file from jar provided path of file present in jar – Manjunath Sep 22 '16 at 11:15