MATSIM
AbstractMatsimWriter.java
Go to the documentation of this file.
1 /* *********************************************************************** *
2  * project: org.matsim.*
3  * MatsimWriter.java
4  * *
5  * *********************************************************************** *
6  * *
7  * copyright : (C) 2007 by the members listed in the COPYING, *
8  * LICENSE and WARRANTY file. *
9  * email : info at matsim dot org *
10  * *
11  * *********************************************************************** *
12  * *
13  * This program is free software; you can redistribute it and/or modify *
14  * it under the terms of the GNU General Public License as published by *
15  * the Free Software Foundation; either version 2 of the License, or *
16  * (at your option) any later version. *
17  * See also COPYING, LICENSE and WARRANTY file *
18  * *
19  * *********************************************************************** */
20 
21 package org.matsim.core.utils.io;
22 
23 import java.io.BufferedWriter;
24 import java.io.IOException;
25 import java.io.OutputStream;
26 import java.io.OutputStreamWriter;
27 import java.io.UncheckedIOException;
28 import java.nio.charset.StandardCharsets;
29 import java.util.zip.GZIPOutputStream;
30 
31 
38 public abstract class AbstractMatsimWriter {
39 
41  protected static final String NL = "\n";
42 
44  protected BufferedWriter writer = null;
45 
49  protected Boolean useCompression = null;
50 
58  public final void useCompression(final boolean useCompression) {
59  this.useCompression = useCompression;
60  }
61 
68  protected final void openFile(final String filename) throws UncheckedIOException {
70  if (this.useCompression == null) {
71  this.writer = IOUtils.getBufferedWriter(filename);
72  } else {
73  this.writer = IOUtils.getBufferedWriter(filename + ".gz");
74  }
75  }
76 
81  protected final void openOutputStream(OutputStream outputStream) {
83  try {
84  if (this.useCompression == null || this.useCompression) {
85  this.writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
86  } else {
87  this.writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(outputStream), StandardCharsets.UTF_8));
88  }
89  } catch (IOException e) {
90  throw new UncheckedIOException(e);
91  }
92  }
93 
94  private void assertNotAlreadyOpen() {
95  if (this.writer != null) {
96  throw new RuntimeException("File already open.");
97  }
98  }
99 
105  protected final void close() throws UncheckedIOException {
106  if (this.writer != null) {
107  try {
108  this.writer.flush();
109  this.writer.close();
110  } catch (IOException e) {
111  throw new UncheckedIOException(e);
112  } finally {
113  this.writer = null;
114  }
115  }
116  }
117 
118 }
static BufferedWriter getBufferedWriter(URL url, Charset charset, boolean append)
Definition: IOUtils.java:390
final void openOutputStream(OutputStream outputStream)
final void useCompression(final boolean useCompression)