如何在Java中查找非常大的文件复制状态

我需要监视目录中文件的复制状态,并将文件连续放置到java中的目录中.
我打算使用Executor框架找出单个文件的复制状态,并且我已经编写了以下代码,但未按预期工作,没有复制完成的文件,复制完成后我收到通知.

private boolean isFileCopied(String filePath) {
    File file = new File(filePath);

    Scanner scanner;
    boolean isCopied = true;
    while (true) {
        try {
            scanner = new Scanner(file);
            isCopied = false;
        } catch (FileNotFoundException e) {
            System.out.println(filePath + " File is in copy State. ");
            sleepFile();
        }
        if (isCopied == false) {
            break;
        }
    }
    System.out.println(filePath + "  copy completed");
    return isCopied;
}

   private static void sleepFile() {
    System.out.println("sleeping for 10 seconds");
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

请有人帮助我,如何找到文件“正在复制”或“复制完成”之类文件的确切状态,以及如何监视每个文件的复制状态(如果将大量文件放在目录中).

我曾经使用过watcher API,但不能解决我的目的.甚至没有复制的文件也完成了,但复制完成了,我也收到了通知.以下是我的代码更改.

使用观察者服务:

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class FolderWatchDemo {
public static void main(String[] args) {

    final Path outputWatchFolderPath =  Paths.get("/outputFolder/");
    final Path sourceFolderPath = Paths.get("/sourceFolder/");

    try {
        //Registering outputWatchFolderPath
        WatchService watcher = FileSystems.getDefault().newWatchService();
        Path dir = Paths.get(outputWatchFolderPath.toString());

        dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        System.out.println("Watch Service registered for dir: " + dir.getFileName());

        //copy files from inputfolder to o
        for (final Path path: Files.newDirectoryStream(sourceFolderPath))
            Files.copy(path, outputWatchFolderPath.resolve(path.getFileName()));

        while (true) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException ex) {
                return;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                 WatchEvent.Kind<?> kind = event.kind();

                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                if (kind == ENTRY_CREATE) {
                    System.out.println("file got created !!");
                }
                if (kind == ENTRY_MODIFY) {
                    System.out.println("copying got completed !!");
                }
                if (kind == ENTRY_DELETE) {
                    System.out.println("file deleted successfully !!");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }

    } catch (IOException ex) {
        System.err.println(ex);
    }
}
}

提前致谢.

解决方法:

创建回叫系统并通过实现ReadableByteChannel来实现它的一种非常优雅的方法,以便监视复制文件的进度.另外,好处是无需监视目录.您可以显式监视正在复制的文件的进度.

主要想法是由this站点提出的,但对其进行了一些更改以适合您的问题:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;

interface ProgressCallBack {
    public void callback(CallbackByteChannel rbc, double progress);
}   

public class Main{
    public static void main(String[] args) {

        ProgressCallBack progressCallBack = new ProgressCallBack() {
            @Override
            public void callback(CallbackByteChannel rbc, double progress) {
                System.out.println(rbc.getReadSoFar());
                System.out.println(progress);
            }
        };

        try {
            copy("SOURCE FILE PATH", "DESTINATION FILE PATH", progressCallBack);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copy(String source, String destination, ProgressCallBack callBack) throws IOException {
        FileOutputStream fos = null;
        FileChannel sourceChannel = null;
        try {
            sourceChannel = new FileInputStream(new File(source)).getChannel();
            ReadableByteChannel rbc = new CallbackByteChannel(sourceChannel, Files.size(Paths.get(source)), callBack);
            fos = new FileOutputStream(destination);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(sourceChannel.isOpen()){
                sourceChannel.close();
            }
            fos.close();
        }
    }
}

class CallbackByteChannel implements ReadableByteChannel {
    ProgressCallBack delegate;
    long size;
    ReadableByteChannel rbc;
    long sizeRead;

    CallbackByteChannel(ReadableByteChannel rbc, long expectedSize, ProgressCallBack delegate) {
        this.delegate = delegate;
        this.size = expectedSize;
        this.rbc = rbc;
    }

    public void close() throws IOException {
        rbc.close();
    }

    public long getReadSoFar() {
        return sizeRead;
    }

    public boolean isOpen() {
        return rbc.isOpen();
    }

    public int read(ByteBuffer bb) throws IOException {
        int n;
        double progress;
        if ((n = rbc.read(bb)) > 0) {
            sizeRead += n;
            progress = size > 0 ? (double) sizeRead / (double) size * 100.0 : -1.0;
            delegate.callback(this, progress);
        }
        return n;
    }
}

希望对您有所帮助.

上一篇:SpringBoot - 使用ExecutorService线程池执行异步任务教程(Runnable任务为例)


下一篇:java-检测当前线程是否为ExecutorService线程