1 package org.apache.archiva.common.utils;
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 import java.io.IOException;
25 import java.io.UncheckedIOException;
26 import java.nio.charset.Charset;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.nio.file.StandardOpenOption;
31 import java.util.Comparator;
32 import java.util.Optional;
36 * Utility class for file manipulation
38 * @author Martin Stockhammer <martin_s@apache.org>
40 public class FileUtils
42 private static final Logger log = LoggerFactory.getLogger( FileUtils.class );
44 * Deletes the directory recursively and quietly.
48 public static void deleteQuietly(Path dir) {
52 .sorted( Comparator.reverseOrder())
58 catch ( IOException e )
65 catch ( IOException e )
73 public static void deleteDirectory( Path dir ) throws IOException
75 if (!Files.exists(dir)) {
78 if (!Files.isDirectory( dir )) {
79 throw new IOException("Given path is not a directory "+dir);
81 boolean result = true;
84 result = Files.walk( dir )
85 .sorted( Comparator.reverseOrder( ) )
91 return Optional.of( Boolean.TRUE );
93 catch ( UncheckedIOException | IOException e )
95 log.warn( "File could not be deleted {}", file );
96 return Optional.empty( );
99 } ).allMatch( Optional::isPresent );
100 } catch (UncheckedIOException e) {
101 throw new IOException("File deletion failed ", e);
104 throw new IOException("Error during recursive delete of "+dir.toAbsolutePath());
108 public static String readFileToString( Path file, Charset encoding)
112 return new String(Files.readAllBytes( file ), encoding );
114 catch ( IOException e )
116 log.error("Could not read from file {}", file);
121 public static void writeStringToFile( Path file, Charset encoding, String value )
125 Files.write( file, value.getBytes( encoding ), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
127 catch ( IOException e )
129 log.error("Could not write to file {}", file);
134 * Return the base directory
137 public static String getBasedir()
139 String basedir = System.getProperty( "basedir" );
140 if ( basedir == null )
142 basedir = Paths.get("").toAbsolutePath().toString();