2013-04-26 59 views
2

我有3个字符串,其中每个代表一个txt文件内容,不是从计算机加载的,而是由Java生成的。如何使用字符串在java中创建Gzip存档?

String firstFileCon = "firstContent"; //File in .gz: 1.txt 
String secondFileCon = "secondContent"; //File in .gz: 2.txt 
String thirdFileCon = "thirdContent"; //File in .gz: 3.txt 

如何创建一个GZIP文件,里面有三个文件,并将压缩文件保存到光盘?

+0

字符串是否保存要压缩的文件的文件名,或者你想压缩字符串本身吗? – Jias 2013-04-26 19:29:32

回答

2

创建一个名为zip文件output.zip包含文件1.txt的2.txt3.txt他们的内容字符串,请尝试以下操作:

Map<String, String> entries = new HashMap<String, String>(); 
entries.put("firstContent", "1.txt"); 
entries.put("secondContent", "2.txt"); 
entries.put("thirdContent", "3.txt"); 

FileOutputStream fos = null; 
ZipOutputStream zos = null; 
try { 
    fos = new FileOutputStream("output.zip"); 

    zos = new ZipOutputStream(fos); 

    for (Map.Entry<String, String> mapEntry : entries.entrySet()) { 
     ZipEntry entry = new ZipEntry(mapEntry.getValue()); // create a new zip file entry with name, e.g. "1.txt" 
     entry.setMethod(ZipEntry.DEFLATED); // set the compression method 
     zos.putNextEntry(entry); // add the ZipEntry to the ZipOutputStream 
     zos.write(mapEntry.getKey().getBytes()); // write the ZipEntry content 
    } 
} catch (FileNotFoundException e) { 
    // do something 
} catch (IOException e) { 
    // do something 
} finally { 
    if (zos != null) { 
     zos.close(); 
    } 
} 

有关更多信息,请参阅Creating ZIP and JAR files,特别是章节压缩文件

0

一般来说,GZIP仅用于压缩单个文件(因此为什么java.util.zip.GZIPOutputStream只能真正支持单个条目)。

对于多个文件,我建议使用专为多个文件(如zip)设计的格式。 java.util.zip.ZipOutputStream就是这样。如果出于某种原因,您确实希望最终结果为GZIP,那么您始终可以创建一个包含所有3个文件然后是GZIP的ZIP文件。

0

目前还不清楚您是否只想存储文本或实际的单个文件。我不认为你可以在没有第一次TARING的情况下将多个文件存储在GZIP中。这里是一个存储字符串到GZIP的例子。也许它会帮助你:

public static void main(String[] args) { 
    GZIPOutputStream gos = null; 

    try { 
     String str = "some string here..."; 
     File myGzipFile = new File("myFile.gzip"); 

     InputStream is = new ByteArrayInputStream(str.getBytes()); 
     gos = new GZIPOutputStream(new FileOutputStream(myGzipFile)); 

     byte[] buffer = new byte[1024]; 
     int len; 
     while ((len = is.read(buffer)) != -1) { 
      gos.write(buffer, 0, len); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { gos.close(); } catch (IOException e) { } 
    } 
} 
相关问题