File operations
delete
Following method allows delete file or folder. Folder can be non-empty.
public static void deleteFile(File f) throws IOException {
try(Stream<Path> stream = Files.walk(f.toPath())) {
stream.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
You can replace File.delete() with Files.delete(), which may throw more exceptions.
clean folder
Following method allows to clean folder, without deleting itself.
public static void cleanDir(File dir) throws IOException {
if (dir.isDirectory()) {
try (Stream<Path> stream = Files.walk(dir.toPath())) {
stream.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(f -> {
if (!dir.equals(f)) f.delete();
});
}
}
}
copy files
Following method allows copy content of one file to another.
public static boolean copyFiles(File src, File dst,
ProgressListener progressListener,
ErrorHandler errorHandler) {
dst.getParentFile().mkdirs();
long total = src.length();
long current = 0L;
try (InputStream in = new BufferedInputStream(new FileInputStream(src));
OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
current += length;
if (progressListener != null) {
progressListener.onProgress(current, total);
}
}
} catch (Exception e) {
e.printStackTrace();
if (errorHandler != null) {
errorHandler.onError(e);
}
return false;
}
return true;
}
If you don't need callbacks:
public static void copyFiles(File src, File dst)
throws IOException {
dst.getParentFile().mkdirs();
Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
}