2012-11-09 60 views
1

在我的應用程序中,我使用html模板和瀏覽器字段的圖像並保存在SD卡中。現在我想壓縮該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()); 
      } 
     } 
    } 

} 

此代碼工作正常,爲單個文件,但我想壓縮所有文件(更多的一個文件)在文件夾中。

+0

您可以使用'GZIPOutputStream'或'ZLibOutputStream'。 –

回答

2

如果你不熟悉它們,我可以告訴你,在Java中,流類遵循Decorator Pattern。這些旨在被傳送到其他流以執行其他任務。例如,一個FileOutputStream允許你寫一個字節到一個文件,如果你用BufferedOutputStream來修飾它,那麼你也可以緩衝(在最終寫入光盤之前,大塊的數據存儲在RAM中)。或者如果你用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")); 

這是一個good tutorial覆蓋基本I/O。儘管是爲JavaSE編寫的,但您會發現它很有用,因爲大多數情況在BlackBerry中都是一樣的。

在API你有這些類可供選擇:
GZIPInputStream
GZIPOutputStream
ZLibInputStream
ZLibOutputStream

如果您需要流和字節數組之間轉換使用IOUtilities類或ByteArrayOutputStreamByteArrayInputStream

+0

嗨史密斯先生感謝您的重播...我按照你的方式我得到了java.long.illegalArgumentException:錯誤的API使用javax.microedition.io.file ...我編輯我的問題,請看看 – prakash

+0

您可能正在使用' java.io.FileInputStream'和'java.io.FileOutputStream'。試試'net.rim.device.api.io.FileInputStream'和'net.rim.device.api.io.FileOutputStream'。 –

+0

順便說一句,創建的文件不是ZIP文件。一個ZIP文件被壓縮,但也是一個容器,可以包含多個文件和文件夾。你當然可以按你的意願命名。 –