Tengo la duda de como saber cual es el conteo parcial de los documentos en un directorio mientras se usa Files.walk, ya que si el directorio contiene mas de un millon de archivo y le toma 10 min en contabilizar todo, quiero saber cada 1 min por ejemplo el conteo que lleva hasta ese momento y no esperar a que totalice. Es el mismo proceso cuando quieres borrar un directorio en cualquier sistema operativo que primero te va mostrando como va contando la cantidad de archivos indexados hasta la totalizacion para luego borrar todo.
1 respuesta
De acuerdo a la documentación de Files.Walk
(Javadoc) esto no es posible. dado a que este método no posee forma de registrar un "listener", o algun evento que nos indique de resultados parciales, pero por otro lado con Files.walkFileTree
(Javadoc) si es posible puesto puedes implementar un conteo, o manipulación más a tu gusto.
en el siguiente ejemplo se Utiliza un SwingWorker (Javadoc) con resultados intermedios que son enviados via el metodo publish
al UI UI
y el resultado final se puede obtener via get()
:
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
public abstract class SwingWalter extends SwingWorker<String, String> {
private int counter = 0;
private long lastpublishTime;
private final Path Root;
public SwingWalter(Path tonavigate) {
Root = tonavigate;
}
@Override
protected String doInBackground() throws Exception {
lastpublishTime = System.currentTimeMillis();
Files.walkFileTree(Root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (System.currentTimeMillis() - lastpublishTime > 5000) {
publish(String.format("Current PathCount: %s, navigating to Path: %s ", counter, dir.toString()));
lastpublishTime = System.currentTimeMillis();
}
counter++;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (System.currentTimeMillis() - lastpublishTime > 5000) {
publish(String.format("Current PathCount: %s, looking at: %s ", counter, file.toString()));
lastpublishTime = System.currentTimeMillis();
}
counter++;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
publish(String.format("unable to visit Path: %s , ignoring...", file.toString()));
return FileVisitResult.CONTINUE;
}
});
return String.format("Files on %s are: %s ", Root.toString(), counter);
}
@Override
protected final void process(List<String> chunks) {
UpdateUIText(String.join(System.lineSeparator(), chunks));
}
@Override
protected final void done() {
try {
UpdateUIText(String.format("%s%s","Task Completed result: ", get()));
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
}
completed();
}
/*este metodo es llamado via el EDT(event dispatch thread)
el cual es un hilo de ejecucion seguro para actualizar
componentes de Swing)*/
protected abstract void UpdateUIText(String Text);
/*este metodo es llamado via el EDT (hilo de ejecucion seguro para
actualizar componentes de Swing),
este se llama cuando el SwingWalter concluye su ejecucion
por tanto este lo pude utilizar para cambiar estados que requieren
que finalize el "background task"
*/
protected abstract void completed();
}
para utilizar este SwingWorker se realiza de una manera similar a:
//....
private SwingWorker<String, String> tmpworker;
private javax.swing.JButton Btexecute;
private javax.swing.JTextArea txtOutput;
//....
//definicion del UI Y metodos etc...
//....
private SwingWorker<String, String> getWorker(Path tonavigate) {
return new SwingWalter(tonavigate) {
@Override
protected void UpdateUIText(String Text) {
try {
//txtouput es un TextArea
txtOutput.getDocument().insertString(txtOutput.getDocument().getLength(), String.format("%s%s", System.lineSeparator(),Text), null);
} catch (BadLocationException ex) {
Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void completed() {
//free something unlock a button maybe?
}
};
}
//...
//BtexecuteActionPerformed es el evento de un botton que ejecuta el Swingworker
private void BtexecuteActionPerformed(java.awt.event.ActionEvent evt) {
if (tmpworker == null || tmpworker.isDone()) {
tmpworker = getWorker(Paths.get("C:\\"));
tmpworker.execute();
}
}
NOTA:
en el ejemplo utilizo if (System.currentTimeMillis() - lastpublishTime > 5000) {
para asegurar que por cada archivo que se navegue si ah transcurido 5000
o mas Milisegundos
o 5 segundos
realize un Publish al UI con el archivo que actualmente este navegando.