View Javadoc
1   package org.opentrafficsim.base;
2   
3   import java.io.BufferedWriter;
4   import java.io.File;
5   import java.io.FileOutputStream;
6   import java.io.IOException;
7   import java.io.OutputStreamWriter;
8   import java.util.zip.ZipEntry;
9   import java.util.zip.ZipOutputStream;
10  
11  /**
12   * File writer.
13   * <p>
14   * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
15   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
16   * <p>
17   * @version $Revision$, $LastChangedDate$, by $Author$, initial version 2 mei 2018 <br>
18   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
19   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
20   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
21   */
22  public final class CompressedFileWriter
23  {
24  
25      /**
26       * Constructor.
27       */
28      private CompressedFileWriter()
29      {
30          // utility
31      }
32  
33      /**
34       * Returns a {@code BufferedWriter} to a file, zipped or not.
35       * @param file String; file
36       * @param zipped boolean; zipped or not
37       * @return BufferedWriter
38       */
39      public static BufferedWriter create(final String file, final boolean zipped)
40      {
41          String name = null;
42          String file2 = file;
43          if (zipped)
44          {
45              File f = new File(file);
46              name = f.getName();
47              if (!file.endsWith(".zip"))
48              {
49                  file2 += ".zip";
50              }
51          }
52          try
53          {
54              FileOutputStream fos = new FileOutputStream(file2);
55              OutputStreamWriter osw;
56              if (zipped)
57              {
58                  ZipOutputStream zos = new ZipOutputStream(fos);
59                  zos.putNextEntry(new ZipEntry(name));
60                  osw = new OutputStreamWriter(zos);
61              }
62              else
63              {
64                  osw = new OutputStreamWriter(fos);
65              }
66              return new BufferedWriter(osw);
67          }
68          catch (IOException exception)
69          {
70              throw new RuntimeException("Could not write to file.", exception);
71          }
72      }
73  
74  }