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