在BlackBerry Java app中压缩文件

时间:2010-12-27 07:16:55

标签: java blackberry java-me

是否有人知道如何使用 ZipOutputStream 压缩文件?

try {
    // Creating Zip Streams
    FileConnection path = (FileConnection) Connector.open(
            "file:///SDCard/BlackBerry/documents/" + "status.zip",
            Connector.READ_WRITE);

    if (!path.exists()) {
        path.create();
    }
    ZipOutputStream zinstream = new ZipOutputStream(
            path.openOutputStream());

    // Adding Entries
    FileConnection jsonfile = (FileConnection) Connector.open(
            "file:///SDCard/BlackBerry/documents/" + "status.json",
            Connector.READ_WRITE);
    if (!jsonfile.exists()) {
        jsonfile.create();
    }
    int fileSize = (int) jsonfile.fileSize();
    if (fileSize > -1) {
        byte[] data = new byte[fileSize];
        InputStream input = jsonfile.openInputStream();
        input.read(data);

        ZipEntry entry = new ZipEntry(jsonfile.getName());
        zinstream.putNextEntry(entry);
        // zinstream.write(buf);
        // ZipEntry entry = null;

        path.setWritable(true);
        OutputStream out = path.openOutputStream();

        int len;
        while ((len = input.read(data)) != -1) {
            out.write(data, 0, len);
            out.flush();
            out.close();
            zinstream.close();
            content = "FILE EXIST" + entry;
        }

        jsonfile.close();
        path.close();
    }
} catch (...) {
    ...
}

2 个答案:

答案 0 :(得分:3)

应将数据写入 ZipOutputStream zinstream ,而不是写入新的 OutputStream out

完成写作后关闭 ZipEntry 条目也很重要。

FileConnection path = (FileConnection) Connector.open(
        "file:///SDCard/BlackBerry/documents/" + "status.zip",
        Connector.READ_WRITE);

if (!path.exists()) {
    path.create();
}
ZipOutputStream zinstream = new ZipOutputStream(path.openOutputStream());

// Adding Entries
FileConnection jsonfile = (FileConnection) Connector.open(
        "file:///SDCard/BlackBerry/documents/" + "status.json",
        Connector.READ_WRITE);
if (!jsonfile.exists()) {
    jsonfile.create();
}
int fileSize = (int) jsonfile.fileSize();
if (fileSize > -1) {
    InputStream input = jsonfile.openInputStream();
    byte[] data = new byte[1024];

    ZipEntry entry = new ZipEntry(jsonfile.getName());
    zinstream.putNextEntry(entry);

    int len;
    while ((len = input.read(data)) > 0) {
        zinstream.write(data, 0, len);
    }
    zinstream.closeEntry();
}
jsonfile.close();
zinstream.close();
path.close();

答案 1 :(得分:2)

BlackBerry使用的J2ME API没有所有J2SE类,例如ZipOutputStream和ZipEntry以及相关的类。有一些类,比如ZLibOutputStream可能有帮助,但这只是字节级压缩,你最终必须自己实现实际的PKZIP容器(除非那里有第三方库可以做到这一点)你)。