簡體   English   中英

將文件從一個目錄復制到另一個目錄,並使用時間戳附加新文件,而不是用Java覆蓋

[英]Copy files from one directory to another and append new files with timestamp instead of overwriting in Java

我想將文件從源目錄復制到目標。 如果該文件已存在於目標目錄中,則將要復制的新文件及其時間戳附加在文件上,以免覆蓋。 如何檢查重復項並將時間戳附加到新文件名? 請幫忙!

public static void copyFolder(File src, File dest)
    throws IOException{
        //list all the directory contents
        String files[] = src.list();
        for (String file : files) {
           //construct the src and dest file structure
           File srcFile = new File(src, file);
           File destFile = new File(dest, file);
           //recursive copy
           copyFolder(srcFile,destFile);
        }
    }else{
        //if file, then copy it
        //Use bytes stream to support all file types
        InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
        int length;
            //copy the file content in bytes
            while ((length = in.read(buffer)) > 0){
               out.write(buffer, 0, length);
            }

            in.close();
            out.close();
            System.out.println("File copied from " + src + " to " + dest);
    }
}

您可以使用File.exist()方法檢查文件是否存在,如果存在,則可以以追加模式打開文件

代碼是這樣的

File f = new File(oldName);
if(f.exists() && !f.isDirectory()) { 
    long currentTime=System.currentTimeMillis();
    String newName=oldName+currentTime;
    // do the copy

}
    //construct the src and dest file structure
    File srcFile = new File(src, file);
    File destFile = new File(dest, file);
    while (destFile.exists()) {
        destFile = new File(dest, file + '-' + Instant.now());
    }

在一種情況下,目標文件名為test-file.txt-2018-03-14T11:05:21.103706Z 給定的時間以UTC為單位。 無論如何,您最終都會得到一個尚不存在的文件名(如果循環終止,但是我很難看到它不存在的情況)。

您可能只想將時間戳附加到純文件並重用現有的文件夾(目錄),在這里我不知道您的要求。 如果有一個時間戳,您可能希望在擴展名之前附加時間戳(以獲取test-file-2018-03-14T11:05:21.103706Z.txt代替)。 我相信您可以進行必要的修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM