br.com.objectos.io.Directory Maven / Gradle / Ivy
/*
* Copyright 2013-present Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.io;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.stream.Stream;
/**
* @author [email protected] (Marcio Endo)
*/
public final class Directory extends Node {
public static final Directory JAVA_IO_TMPDIR = fromSystemProperty("java.io.tmpdir");
public static final Directory USER_HOME = fromSystemProperty("user.home");
private Directory(Path dir) {
super(dir);
}
public static Directory at(String path) {
File dir = new File(path);
return at(dir);
}
public static Directory at(File dir) {
dir.mkdirs();
return new Directory(dir.toPath());
}
public static Directory parentOf(File child) {
File parent = child.getParentFile();
return new Directory(parent.toPath());
}
private static Directory fromSystemProperty(String propertyName) {
String property = System.getProperty(propertyName);
return Directory.at(property);
}
public void clear() throws IOException {
stream().forEach(Node::deleteUnchecked);
}
@Override
public void delete() {
rm_rf();
}
public Directory dirAt(String child) {
File dir = new File(delegate().toFile(), child);
dir.mkdirs();
return new Directory(dir.toPath());
}
public br.com.objectos.io.File fileAt(String child) {
Objects.requireNonNull(child);
Path path = Paths.get(delegate().toString(), child);
return br.com.objectos.io.File.of(path);
}
@Override
public boolean isDirectory() {
return true;
}
public void rm_rf() {
rm_rf0(delegate().toFile());
}
public Stream stream() {
try {
return exists()
? Files.walk(delegate())
.filter(o -> !o.equals(delegate()))
.map(Node::of)
: Stream.empty();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String getAbsolutePath() {
return toString();
}
File getParent() {
return delegate().toFile();
}
private void rm_rf0(File dir) {
File[] list = dir.listFiles();
if (list != null) {
for (File child : list) {
if (child.isDirectory()) {
rm_rf0(child);
}
child.delete();
}
}
dir.delete();
}
}