繁体   English   中英

在BlackBerry Java应用中压缩文件

[英]Zip a file in BlackBerry Java app

有谁知道如何使用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 (...) {
    ...
}

数据应写入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();

BlackBerry使用的J2ME API并不具有所有的J2SE类,例如ZipOutputStream和ZipEntry及其相关类。 有一些类,例如ZLibOutputStream可能会有所帮助,但这只是字节级压缩,您最终将不得不自己实现实际的PKZIP容器(除非那里有第三方库可以为您)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM