0

我开发了一个将文件从源文件夹复制到目标文件夹的 java 程序,它有 10 个序列化文件从源文件夹复制到目标文件夹

但是其中缺少的一件事是,如果文件已经存在于目标文件夹中,那么在这种情况下它不应该复制,所以基本上在一秒钟内完成查看,以检查目标文件夹是否包含这 10 个序列化文件如果不是,那么在这种情况下,只有它应该复制,复制后它应该在第二秒内再次检查文件是否存在,请告知如何实现这一点

//Create a class extends with TimerTask
class ScheduledTask extends TimerTask {

    public void run() {
        InputStream inStream = null;
        OutputStream outStream = null;

        try {
            File source = new File("C:\\cache\\");
            File target = new File("C:\\Authclient\\cache\\");

            // Already exists. do not copy
            /*if (target.exists()) { 
                return;
            }*/

            File[] files = source.listFiles();
            for (File file : files) {
                inStream = new FileInputStream(file);
                outStream = new FileOutputStream(target + "/" + file.getName());

                byte[] buffer = new byte[1024];
                int length;
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, length);
                }
                inStream.close();
                outStream.close();
            }
            System.out.println("File is copied successful!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class Copycache {
    public static void main(String args[]) throws InterruptedException  {
        Timer time = new Timer();
        ScheduledTask task = new ScheduledTask();
        time.schedule(task, new Date(), TimeUnit.SECONDS.toMillis(1));
    }

}

上面存在的已被评论的实现现在无法正常工作,请告知

4

1 回答 1

0

我很好奇你的确切要求。考虑这个小例子:

File file = new File("test.txt");
if (!file.exists())
{
    FileOutputStream fis = new FileOutputStream(file);
    fis.write("blabla".getBytes());
    fis.close();
}

现在在 FileOutputStream fis... 行放一个断点运行它并在断点处等待,然后手动创建 test.txt 并在其中放入一些数据。然后继续运行程序。

您的程序将在没有警告的情况下覆盖 test.txt 的内容。

如果时间在这里如此重要,您将需要找出不同的解决方案。

编辑:我很好奇并做了更多测试。file.createNewFile();如果您添加该行,在那里中断,创建文件然后继续应用程序,似乎它甚至不会引发异常。我想知道为什么..

于 2013-02-03T10:08:03.203 回答