001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one or more
003 *  contributor license agreements.  See the NOTICE file distributed with
004 *  this work for additional information regarding copyright ownership.
005 *  The ASF licenses this file to You under the Apache License, Version 2.0
006 *  (the "License"); you may not use this file except in compliance with
007 *  the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018package org.apache.commons.compress.parallel;
019
020import java.io.File;
021import java.io.FileNotFoundException;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.nio.file.Files;
026
027/**
028 * ScatterGatherBackingStore that is backed by a file.
029 *
030 * @since 1.10
031 */
032public class FileBasedScatterGatherBackingStore implements ScatterGatherBackingStore {
033    private final File target;
034    private final OutputStream os;
035    private boolean closed;
036
037    public FileBasedScatterGatherBackingStore(final File target) throws FileNotFoundException {
038        this.target = target;
039        try {
040            os = Files.newOutputStream(target.toPath());
041        } catch (FileNotFoundException ex) {
042            throw ex;
043        } catch (IOException ex) {
044            // must convert exception to stay backwards compatible with Compress 1.10 to 1.13
045            throw new RuntimeException(ex); // NOSONAR
046        }
047    }
048
049    @Override
050    public InputStream getInputStream() throws IOException {
051        return Files.newInputStream(target.toPath());
052    }
053
054    @Override
055    @SuppressWarnings("ResultOfMethodCallIgnored")
056    public void closeForWriting() throws IOException {
057        if (!closed) {
058            os.close();
059            closed = true;
060        }
061    }
062
063    @Override
064    public void writeOut(final byte[] data, final int offset, final int length) throws IOException {
065        os.write(data, offset, length);
066    }
067
068    @Override
069    public void close() throws IOException {
070        try {
071            closeForWriting();
072        } finally {
073            target.delete();
074        }
075    }
076}