View Javadoc
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   * http://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  
20  package org.apache.commons.compress.compressors.pack200;
21  
22  import java.io.FilterInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.nio.file.Files;
26  import java.nio.file.Path;
27  
28  /**
29   * StreamBridge that caches all data written to the output side in a temporary file.
30   *
31   * @since 1.3
32   */
33  final class TempFileCachingStreamBridge extends AbstractStreamBridge {
34  
35      private final Path path;
36  
37      TempFileCachingStreamBridge() throws IOException {
38          this.path = Files.createTempFile("commons-compress", "packtemp");
39          this.path.toFile().deleteOnExit();
40          this.out = Files.newOutputStream(path);
41      }
42  
43      @SuppressWarnings("resource") // Caller closes
44      @Override
45      InputStream createInputStream() throws IOException {
46          out.close();
47          return new FilterInputStream(Files.newInputStream(path)) {
48              @Override
49              public void close() throws IOException {
50                  try {
51                      super.close();
52                  } finally {
53                      try {
54                          Files.deleteIfExists(path);
55                      } catch (final IOException ignored) {
56                          // if this fails the only thing we can do is to rely on deleteOnExit
57                      }
58                  }
59              }
60          };
61      }
62  }