1 package org.opentrafficsim.base.compressedfiles;
2
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.util.zip.GZIPOutputStream;
7 import java.util.zip.ZipEntry;
8 import java.util.zip.ZipOutputStream;
9
10 import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
11
12
13
14
15
16
17
18
19
20
21
22
23 public final class Writer
24 {
25
26
27
28 private Writer()
29 {
30
31 }
32
33
34
35
36
37
38
39
40 public static OutputStream createOutputStream(final String fileName, final CompressionType compressionType)
41 throws IOException
42 {
43 if (CompressionType.AUTODETECT.equals(compressionType))
44 {
45 throw new IOException("AUTODETECT not allowed for Writer");
46 }
47 String extension = "." + compressionType.getExtension();
48 int suffixPos = fileName.length() - extension.length();
49 String currentSuffix = suffixPos > 0 ? fileName.substring(suffixPos) : "";
50 String fixedFileName =
51 (currentSuffix.equalsIgnoreCase(extension) ? fileName.substring(0, suffixPos) : fileName) + extension;
52 FileOutputStream fileOutputStream = new FileOutputStream(fixedFileName);
53 switch (compressionType)
54 {
55 case AUTODETECT:
56
57 throw new IOException("AUTODETECT not allowed for Writer");
58
59 case BZIP2:
60 return new BZip2CompressorOutputStream(fileOutputStream);
61
62 case GZIP:
63 return new GZIPOutputStream(fileOutputStream);
64
65 case NONE:
66 return fileOutputStream;
67
68 case ZIP:
69 {
70 ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
71
72 int lastSeparatorPos =
73 Math.max(Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\")), fileName.lastIndexOf(":"));
74 String entryName = fileName.substring(lastSeparatorPos + 1);
75 zipOutputStream.putNextEntry(new ZipEntry(entryName));
76 return zipOutputStream;
77 }
78
79 default:
80
81 throw new IOException("Don't know how to create writer for compression type " + compressionType);
82
83 }
84 }
85
86 }