1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 package org.apache.commons.compress.parallel; 19 20 import java.io.File; 21 import java.io.FileNotFoundException; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.io.OutputStream; 25 import java.nio.file.Files; 26 27 /** 28 * ScatterGatherBackingStore that is backed by a file. 29 * 30 * @since 1.10 31 */ 32 public class FileBasedScatterGatherBackingStore implements ScatterGatherBackingStore { 33 private final File target; 34 private final OutputStream os; 35 private boolean closed; 36 37 public FileBasedScatterGatherBackingStore(final File target) throws FileNotFoundException { 38 this.target = target; 39 try { 40 os = Files.newOutputStream(target.toPath()); 41 } catch (FileNotFoundException ex) { 42 throw ex; 43 } catch (IOException ex) { 44 // must convert exception to stay backwards compatible with Compress 1.10 to 1.13 45 throw new RuntimeException(ex); // NOSONAR 46 } 47 } 48 49 @Override 50 public InputStream getInputStream() throws IOException { 51 return Files.newInputStream(target.toPath()); 52 } 53 54 @Override 55 @SuppressWarnings("ResultOfMethodCallIgnored") 56 public void closeForWriting() throws IOException { 57 if (!closed) { 58 os.close(); 59 closed = true; 60 } 61 } 62 63 @Override 64 public void writeOut(final byte[] data, final int offset, final int length) throws IOException { 65 os.write(data, offset, length); 66 } 67 68 @Override 69 public void close() throws IOException { 70 try { 71 closeForWriting(); 72 } finally { 73 target.delete(); 74 } 75 } 76 } 77