2 * Sonitus - FileSink.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sonitus.data.sink;
20 import java.io.FileNotFoundException;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.util.logging.Logger;
25 import net.pterodactylus.sonitus.data.ConnectException;
26 import net.pterodactylus.sonitus.data.Connection;
27 import net.pterodactylus.sonitus.data.Sink;
28 import net.pterodactylus.sonitus.data.Source;
30 import com.google.common.base.Preconditions;
33 * {@link Sink} that writes all received data into a file.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37 public class FileSink implements Sink {
40 private static final Logger logger = Logger.getLogger(FileSink.class.getName());
42 /** The path of the file to write to. */
43 private final String path;
46 * Creates a new file sink that will write to the given path.
49 * The path of the file to write to
51 public FileSink(String path) {
56 public void connect(Source source) throws ConnectException {
57 Preconditions.checkNotNull(source, "source must not be null");
60 final FileOutputStream fileOutputStream = new FileOutputStream(path);
61 new Thread(new Connection(source) {
64 protected int bufferSize() {
69 protected void feed(byte[] buffer) throws IOException {
70 fileOutputStream.write(buffer);
71 logger.finest(String.format("FileSink: Wrote %d Bytes.", buffer.length));
75 protected void finish() throws IOException {
76 fileOutputStream.close();
79 } catch (FileNotFoundException fnfe1) {
80 throw new ConnectException(fnfe1);