0

仅当目标文件夹不包含该序列化文件时,我才必须制作一个程序将序列化文件从源文件夹复制到目标文件夹,因此第一个条件是检查我正在复制的文件是否已存在于目标文件夹中如果存在则不需要复制,如果不存在则复制,因此需要每秒检查文件是否存在

源文件夹是 C:\ter\ 目标文件夹是 C:\bvg\

要传输的文件是 gfr.ser

我已经提出了以下程序,但仍未实施检查,请告知我如何也实施此检查..

类 ScheduledTask 扩展 TimerTask {

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

    try {
        File source = new File("C:\\ter\\");
        File target = new File("C:\\avd\\bvg\\");

        // 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();
    }
}

}

    the above approach is not working         
4

1 回答 1

3

你可以像这样使用类exists的方法java.io.File

 public void run() {
        InputStream inStream = null;
        OutputStream outStream = null;
        try {
            File source = new File("C:\\ter\\gfr.ser");
            File target = new File(" C:\\bvg\\gfr.ser");
            if (target.exists()){   // Already exists. do not copy
                 return;
            }
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(target);
            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();
        }
    }
于 2013-02-03T07:05:30.313 回答