1

在我的应用程序中,我使用 html 模板和图像作为浏览器字段并保存在 sdcard 中。现在我想压缩那个 html、图像文件并发送到 PHP 服务器。如何压缩该文件并发送到服务器?给我一些可能有帮助的样本。

我试过这种方式......我的代码是

编辑:

private void zipthefile() {
    String out_path = "file:///SDCard/" + "newtemplate.zip";
    String in_path = "file:///SDCard/" + "newtemplate.html";
    InputStream inputStream = null;
    GZIPOutputStream os = null;
    try {
        FileConnection fileConnection = (FileConnection) Connector
                .open(in_path);//read the file from path
        if (fileConnection.exists()) {
            inputStream = fileConnection.openInputStream();
        }

        byte[] buffer = new byte[1024];

        FileConnection path = (FileConnection) Connector
                .open(out_path,
                        Connector.READ_WRITE);//create the out put file path

        if (!path.exists()) {
            path.create();
        }
        os = new GZIPOutputStream(path.openOutputStream());// for create the gzip file

        int c;

        while ((c = inputStream.read()) != -1) {
            os.write(c);
        }
    } catch (Exception e) {
        Dialog.alert("" + e.toString());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                Dialog.alert("" + e.toString());
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
                Dialog.alert("" + e.toString());
            }
        }
    }

}

此代码适用于单个文件,但我想压缩文件夹中的所有文件(多个文件)。

4

1 回答 1

2

如果您不熟悉它们,我可以告诉您,在 Java 中,流类遵循装饰器模式。这些旨在通过管道传输到其他流以执行其他任务。例如, aFileOutputStream允许您将字节写入文件,如果您用 a 装饰它,BufferedOutputStream那么您还可以获得缓冲(大块数据在最终写入磁盘之前存储在 RAM 中)。或者,如果你用 a 装饰它,GZIPOutputStream那么你也会得到压缩。

例子:

//To read compressed file:
InputStream is = new GZIPInputStream(new FileInputStream("full_compressed_file_path_here"));

//To write to a compressed file:
OutputStream os = new GZIPOutputStream(new FileOutputStream("full_compressed_file_path_here"));

这是一个涵盖基本 I/O的好教程。尽管是为 JavaSE 编写的,但您会发现它很有用,因为大多数事情在 BlackBerry 中都是一样的。

在 API 中,您可以使用以下类:
GZIPInputStream
GZIPOutputStream
ZLibInputStream
ZLibOutputStream

如果您需要在流和字节数组之间进行转换,请使用IOUtilitiesclass 或ByteArrayOutputStreamand ByteArrayInputStream

于 2012-11-09T10:48:48.103 回答