This project has retired. For details please refer to its Attic page.
FileUtils xref
View Javadoc
1   package org.apache.archiva.common.utils;
2   /*
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *  http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   */
20  
21  import org.slf4j.Logger;
22  import org.slf4j.LoggerFactory;
23  
24  import java.io.*;
25  import java.nio.charset.Charset;
26  import java.nio.file.Files;
27  import java.nio.file.Path;
28  import java.nio.file.Paths;
29  import java.nio.file.StandardOpenOption;
30  import java.util.Comparator;
31  import java.util.Optional;
32  import java.util.zip.ZipEntry;
33  import java.util.zip.ZipFile;
34  
35  /**
36   * Utility class for file manipulation
37   *
38   * @author Martin Stockhammer <martin_s@apache.org>
39   */
40  public class FileUtils {
41      private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
42  
43      /**
44       * Deletes the directory recursively and quietly.
45       *
46       * @param dir
47       */
48      public static void deleteQuietly(Path dir) {
49          try {
50              Files.walk(dir)
51                      .sorted(Comparator.reverseOrder())
52                      .forEach(file -> {
53                          try {
54                              Files.delete(file);
55                          } catch (IOException e) {
56                              // Ignore this
57                          }
58  
59                      });
60          } catch (IOException e) {
61              // Ignore this
62          }
63  
64  
65      }
66  
67      public static void deleteDirectory(Path dir) throws IOException {
68          if (!Files.exists(dir)) {
69              return;
70          }
71          if (!Files.isDirectory(dir)) {
72              throw new IOException("Given path is not a directory " + dir);
73          }
74          boolean result = true;
75          try {
76              result = Files.walk(dir)
77                      .sorted(Comparator.reverseOrder())
78                      .map(file ->
79                      {
80                          try {
81                              Files.delete(file);
82                              return Optional.of(Boolean.TRUE);
83                          } catch (UncheckedIOException | IOException e) {
84                              log.warn("File could not be deleted {}", file);
85                              return Optional.empty();
86                          }
87  
88                      }).allMatch(Optional::isPresent);
89          } catch (UncheckedIOException e) {
90              throw new IOException("File deletion failed ", e);
91          }
92          if (!result) {
93              throw new IOException("Error during recursive delete of " + dir.toAbsolutePath());
94          }
95      }
96  
97      public static String readFileToString(Path file, Charset encoding) {
98          try {
99              return new String(Files.readAllBytes(file), encoding);
100         } catch (IOException e) {
101             log.error("Could not read from file {}", file);
102             return "";
103         }
104     }
105 
106     public static void writeStringToFile(Path file, Charset encoding, String value) {
107         try {
108             Files.write(file, value.getBytes(encoding), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
109         } catch (IOException e) {
110             log.error("Could not write to file {}", file);
111         }
112     }
113 
114     /**
115      * Return the base directory
116      *
117      * @return
118      */
119     public static String getBasedir() {
120         String basedir = System.getProperty("basedir");
121         if (basedir == null) {
122             basedir = Paths.get("").toAbsolutePath().toString();
123         }
124 
125         return basedir;
126     }
127 
128     /**
129      * This checks, if the given child is a absolute path. If this is the case
130      * the relative path is used.
131      *
132      * @param parent The parent directory
133      * @param child  The child
134      * @return The path parent/child
135      */
136     public Path resolveNonAbsolute(Path parent, String child) {
137         Path childPath = Paths.get(child);
138         if (childPath.isAbsolute()) {
139             return parent.resolve(childPath.getNameCount() > 0 ? childPath.subpath(0, childPath.getNameCount()) : Paths.get(""));
140         } else {
141             return parent.resolve(child);
142         }
143     }
144 
145     public static void unzipFileEntry(ZipFile file, ZipEntry entry, Path destinationPath) throws IOException {
146         InputStream is = file.getInputStream(entry);
147         BufferedInputStream bis = new BufferedInputStream(is);
148         Path uncompressedFilePath = destinationPath.resolve(entry.getName());
149         Path parentPath = uncompressedFilePath.getParent();
150         if (!Files.exists(parentPath)) {
151             Files.createDirectories(parentPath);
152         }
153         Files.createFile(uncompressedFilePath);
154         OutputStream fileOutput = Files.newOutputStream(uncompressedFilePath);
155         while (bis.available() > 0) {
156             fileOutput.write(bis.read());
157         }
158         fileOutput.close();
159     }
160 
161 
162     /**
163      * Unzips a file into a destination directory. It does not update the modification time according the
164      * the date in the zip file. All subdirectories will be created if the zip file contains a directory structure.
165      *
166      * @param zipFile the path to the zip file
167      * @param destinationPath the destination path where the files should be extracted.
168      * @throws IOException if an error occurs during extract.
169      */
170     public static void unzip(Path zipFile, Path destinationPath) throws IOException {
171         try (ZipFile file = new ZipFile(zipFile.toFile())) {
172             file.stream().forEach(e -> {
173                 try {
174                     if (e.isDirectory()) {
175                         Files.createDirectories(destinationPath.resolve(e.getName()));
176                     } else {
177                         unzipFileEntry(file, e, destinationPath);
178                     }
179                 } catch (IOException ex) {
180                     log.error("Error occured during unzip of zipFile={}, entry={}. Message: {}", zipFile, e.getName(), ex.getMessage());
181                 }
182             });
183         }
184     }
185 }