【问题标题】:How to compress multiple file with CBZip2OutputStream如何使用 CBZip2OutputStream 压缩多个文件
【发布时间】:2012-10-23 15:37:06
【问题描述】:

我使用 CBZip2OutputStream 创建一个压缩的 bzip 文件。它有效。

但我想在一个 bzip 文件中压缩多个文件,但不使用 tar 存档。

如果我有 file1、file2、file3,我希望它们在 files.bz2 中,而不是在存档 files.tar.bz2 中。

有可能吗?

【问题讨论】:

    标签: java stream bzip2


    【解决方案1】:

    BZip2 is only a compressor for single files 因此,如果不先将多个文件放入存档文件,就无法将多个文件放入 Bzip2 文件中。

    您可以将自己的文件开始和结束标记放入输出流,但最好使用标准存档格式。

    Apache Commons has TarArchiveOutputStream(和TarArchiveInputStream)在这里很有用。

    【讨论】:

      【解决方案2】:

      我明白了,所以我使用了一个带有 TarOutputStream 类的包:

      public void makingTarArchive(File[] inFiles, String inPathName) throws IOException{
      
          StringBuilder stringBuilder = new StringBuilder(inPathName);
          stringBuilder.append(".tar");
      
          String pathName = stringBuilder.toString() ;
      
          // Output file stream
          FileOutputStream dest = new FileOutputStream(pathName);
      
          // Create a TarOutputStream
          TarOutputStream out = new TarOutputStream( new BufferedOutputStream( dest ) );
      
          for(File f : inFiles){
      
              out.putNextEntry(new TarEntry(f, f.getName()));
              BufferedInputStream origin = new BufferedInputStream(new FileInputStream( f ));
      
              int count;
              byte data[] = new byte[2048];
              while((count = origin.read(data)) != -1) {
      
                  out.write(data, 0, count);
              }
      
              out.flush();
              origin.close();
          }
      
          out.close();
      
          dest.close();
      
          File file = new File(pathName) ;
      
          createBZipFile(file);
      
          boolean success = file.delete();
      
          if (!success) {
              System.out.println("can't delete the .tar file");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-09
        • 1970-01-01
        • 2018-09-23
        • 2014-08-25
        相关资源
        最近更新 更多