com.github.isaichkindanila.crypt.lib.file.FileEraser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of crypt-lib Show documentation
Show all versions of crypt-lib Show documentation
Simple Java library for stream ciphers based encryption
The newest version!
package com.github.isaichkindanila.crypt.lib.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Class used to erase files.
*/
@SuppressWarnings({"WeakerAccess", "NonAtomicOperationOnVolatileField", "ResultOfMethodCallIgnored"})
public class FileEraser {
private final byte[] ZEROS = new byte[IOHandler.BUFFER_SIZE];
private final List files;
private volatile long done;
private long total;
/**
* @param files files to be erased
*/
public FileEraser(File... files) {
this(Arrays.asList(files));
}
/**
* @param files files to be erased
*/
public FileEraser(Collection files) {
this.files = new ArrayList<>();
this.total = 0;
files.forEach(this::populateList);
}
private void populateList(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File f : children) {
populateList(f);
}
}
files.add(file);
} else {
files.add(file);
total += file.length();
}
}
private void eraseFile(File file) throws IOException {
long size = file.length();
if (size > 0) {
int totalLoops = (int) (size / ZEROS.length);
int lastLoop = (int) (size % ZEROS.length);
try (FileOutputStream out = new FileOutputStream(file)) {
for (int i = 0; i < totalLoops; i++) {
out.write(ZEROS);
done += ZEROS.length;
}
out.write(ZEROS, 0, lastLoop);
done += lastLoop;
}
}
}
/**
* Fills files with zeros and then deletes them.
*
* @throws IOException if IOException occurs
*/
public void erase() throws IOException {
for (File f : files) {
if (f.isFile()) {
eraseFile(f);
}
f.delete();
}
}
/**
* Returns value in range [0, 1] representing encryption progress,
* where 0 means "not started yet" and 1 means "already finished".
*
* @return double value in range [0, 1]
*/
public double progress() {
return total == 0 ? 1.0 : 1.0 * done / total;
}
}