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.io.UncheckedIOException; 026import java.nio.file.Files; 027import java.nio.file.Path; 028 029/** 030 * ScatterGatherBackingStore that is backed by a path. 031 * 032 * @since 1.10 033 */ 034public class FileBasedScatterGatherBackingStore implements ScatterGatherBackingStore { 035 private final Path target; 036 private final OutputStream outputStream; 037 private boolean closed; 038 039 public FileBasedScatterGatherBackingStore(final File target) throws FileNotFoundException { 040 this(target.toPath()); 041 } 042 043 /** 044 * Constructs a new instance for the given path. 045 * 046 * @param target The path to offload compressed data into. 047 * @throws FileNotFoundException if the file doesn't exist 048 * @since 1.22 049 */ 050 public FileBasedScatterGatherBackingStore(final Path target) throws FileNotFoundException { 051 this.target = target; 052 try { 053 outputStream = Files.newOutputStream(target); 054 } catch (final FileNotFoundException ex) { 055 throw ex; 056 } catch (final IOException ex) { 057 // must convert exception to stay backwards compatible with Compress 1.10 to 1.13 058 throw new UncheckedIOException(ex); // NOSONAR 059 } 060 } 061 062 @Override 063 public InputStream getInputStream() throws IOException { 064 return Files.newInputStream(target); 065 } 066 067 @Override 068 public void closeForWriting() throws IOException { 069 if (!closed) { 070 outputStream.close(); 071 closed = true; 072 } 073 } 074 075 @Override 076 public void writeOut(final byte[] data, final int offset, final int length) throws IOException { 077 outputStream.write(data, offset, length); 078 } 079 080 @Override 081 public void close() throws IOException { 082 try { 083 closeForWriting(); 084 } finally { 085 Files.deleteIfExists(target); 086 } 087 } 088}