Pull all interfaces into a single interface: Filter.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / sink / FileSink.java
1 /*
2  * Sonitus - FileSink.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sonitus.data.sink;
19
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.util.logging.Logger;
23
24 import net.pterodactylus.sonitus.data.AbstractFilter;
25 import net.pterodactylus.sonitus.data.Metadata;
26
27 /**
28  * {@link net.pterodactylus.sonitus.data.Sink} that writes all received data
29  * into a file.
30  *
31  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
32  */
33 public class FileSink extends AbstractFilter {
34
35         /** The logger. */
36         private static final Logger logger = Logger.getLogger(FileSink.class.getName());
37
38         /** The path of the file to write to. */
39         private final String path;
40
41         /** The output stream writing to the file. */
42         private FileOutputStream fileOutputStream;
43
44         /**
45          * Creates a new file sink that will write to the given path.
46          *
47          * @param path
48          *              The path of the file to write to
49          */
50         public FileSink(String path) {
51                 super(path);
52                 this.path = path;
53         }
54
55         //
56         // FILTER METHODS
57         //
58
59         @Override
60         public void open(Metadata metadata) throws IOException {
61                 fileOutputStream = new FileOutputStream(path);
62                 metadataUpdated(metadata);
63         }
64
65         @Override
66         public void close() {
67                 try {
68                         fileOutputStream.close();
69                 } catch (IOException e) {
70                         /* ignore. */
71                 }
72         }
73
74         @Override
75         public void process(byte[] buffer) throws IOException {
76                 fileOutputStream.write(buffer);
77                 logger.finest(String.format("FileSink: Wrote %d Bytes.", buffer.length));
78         }
79
80 }