1

ファイルパスのリストからzipファイルを作成しようとしています。zip ファイルをバイト配列にして、ResponseEntity オブジェクトとして Web ページに返すことができるようにしたかったのです。問題は、 FileOutputStreamを試したときに動作することです。ByteArrayOutputStreamを試しましたが、zip ファイルが破損しています。以下はコードです

//FileOutputStream bos = new FileOutputStream("C:\\files\\zipfile.zip");  
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
ArrayList<String> filepaths = getAllFiles();
byte[] contents = null;

for(String path : filepaths) {
    File pdf = new File(path);

    FileInputStream fis = new FileInputStream(pdf);

    ZipEntry zipEntry = new ZipEntry(path.substring(path.lastIndexOf(File.separator)+1));
    zos.putNextEntry(zipEntry);

    byte[] buffer = new byte[1024];
    int len;
    while ((len = fis.read(buffer)) > 0) {
        zos.write(buffer,0,len);
    }

    fis.close();
    zos.closeEntry();
    zos.flush();

}
contents = new byte[bos.size()];
contents = bos.toByteArray();

zos.close();
bos.close();

上記の最初の 2 行については、ByteArrayOutputStreamを使用すると、zip ファイルが破損しているようです。しかし、FileOutputstreamを使用すると、zip ファイルとそのコンテンツを開くことができません。

zipバイト配列をWebページに送り返す方法は次のとおりです。これらのコードはすべて、スプリング コントローラー メソッド内で発生します。

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/zip"));
headers.setContentDispositionFormData(zipfileNm, zipfileNm);

ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
4

1 に答える 1

0

Have a look at Google's GUAVA library. It allow to easily copy Input to Output Streams. Also check Apache Commons Compress with special ZIP support.

However you might be able to make your life much easier...
The HTTPResponse has an OutputStream object. Instead of shuffling byte arrays through functions, you should obtain that OutputStream and hand it as a parameter to your ZIP creation function. This way you avoid requiring all the memory for the byte shuffling and the potential issues it brings with it.

Hope that helps!

于 2014-04-29T16:15:30.487 に答える