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