帮助我将使用字节的Java代码翻译成jython代码

时间:2008-11-21 08:30:51

标签: java python jython

如何将此代码翻译成jython?

     ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file + ".zip"));
     byte[] buf = new byte[1024];
     int len;
     //Create a new Zip entry with the file's name.
     ZipEntry zipEntry = new ZipEntry(file.toString());
     //Create a buffered input stream out of the file
     //we're trying to add into the Zip archive.
     FileInputStream fin = new FileInputStream(file);
     BufferedInputStream in = new BufferedInputStream(fin);
     zos.putNextEntry(zipEntry);
     //Read bytes from the file and write into the Zip archive.
     while ((len = in.read(buf)) >= 0) {
        zos.write(buf, 0, len);
     }
     //Close the input stream.
     in.close();
     //Close this entry in the Zip stream.
     zos.closeEntry();

这就是我所拥有的,但它失败了

            buf=None                                     <<<< ?
            len=None                                     <<<< ?
            zipEntry=ZipEntry(file.toString()) 
            fin=FileInputStream(file)
            bin=BufferedInputStream(fin)
            self._zos.putNextEntry(zipEntry)
            while (len=bin.helpme_im_dying(buf)) >= 0):  <<<< ?
                self._zos.write(buf,0,len)               <<<< ?
                len = bin.read(buf)                      <<<< ?
            bin.close()
            self._zos.closeEntry()

请参阅此页面以获取信息https://www.acm.org/crossroads/xrds6-3/ovp63.html

3 个答案:

答案 0 :(得分:4)

以下是该功能的精确翻译(除了您的情况,使用bin而不是保留关键字in)。

from jarray import zeros
from java.io import BufferedInputStream, FileInputStream, FileOutputStream
from java.util.zip import ZipEntry, ZipOutputStream

def test(file):
    zos = ZipOutputStream(FileOutputStream(file + ".zip"))
    buf = zeros(1024, 'b')
    zipEntry = ZipEntry(file)
    fin = FileInputStream(file)
    bin = BufferedInputStream(fin)
    zos.putNextEntry(zipEntry)
    len = bin.read(buf)
    while len >= 0:
        zos.write(buf, 0, len)
        len = bin.read(buf)
    bin.close()
    zos.closeEntry()

答案 1 :(得分:1)

这不是你问题的答案,而是相关的。这是一个CPython版本:

from zipfile import ZipFile, ZIP_DEFLATED

def test(file):
    ZipFile(file+".zip", "w", ZIP_DEFLATED).write(file)

答案 2 :(得分:0)

如果没有确保关闭ZipFile,请不要使用它:

with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')