2017-03-23 26 views
3

文字列で変換されたXMLのリストを圧縮しようとしていて、zipファイルに保存して、安静時のPOSTの本体として戻しています。しかし、ファイルを保存するたびに「アーカイブは不明な形式か破損しています」というエラーが表示されます。ZipOutPutStreamでファイルを圧縮するJava

protected ByteArrayOutputStream zip(Map<String, String> mapConvertedXml) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ZipOutputStream zos = new ZipOutputStream(baos); 
    try { 
     for(Map.Entry<String, String> current : mapConvertedXml.entrySet()){ 

      ZipEntry entry = new ZipEntry(current.getKey() + ".xml"); 
      entry.setSize(current.getValue().length()); 
      zos.putNextEntry(entry); 
      zos.write(current.getValue().getBytes()); 
      zos.flush(); 
     } 

     zos.close(); 

    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } 
    return baos; 
} 

誰でも私を助けることができますか?

+0

ネットワークに転送する前にzipファイルをチェックしてみましたか? – nandsito

+1

使用している文字セットは何ですか? Stringの長さがバイト配列の長さと常に一致するわけではないためです。 – Boschi

+0

@nandsitoいいえZipOutputStreamにはそのための関数がありますか? –

答えて

0

zipファイルをテストするには、一時的にファイルシステムに保存して手動で開きます。

FileOutputStream fos = new FileOutputStream(pathToZipFile); 
ZipOutputStream zos = new ZipOutputStream(fos); 

次に、そのようなものを使用してRestサーバーを構築し、ファイルを返すことができます。

public static Response getFileLast(@Context UriInfo ui, @Context HttpHeaders hh) { 
    Response response = null; 
    byte[] sucess = null; 
    ByteArrayOutputStream baos = getYourFile(); 
    sucess = baos.toByteArray(); 
    if(sucess!=null) { 
     response = Response.ok(sucess, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition","attachment; filename = YourFileName").build(); 
    } else { 
     response = Response.status(Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(new Error("Error downloading file.")).build(); 
    } 

    return response; 
} 

たとえば、Advanced Rest Clientをテストできます。

関連する問題