簡體   English   中英

將文件從一個文件夾復制到另一個文件夾,並使用舊文件名和時間戳將文件重命名到新文件夾中

[英]Copy a file from one folder to another folder and rename the file in the new folder with old filename+timestamp

我想將Word文檔從一個文件夾復制到另一個文件夾。 在新文件夾中,文件名應為oldFileName + timeStamp。 我到目前為止:

    public static void main(String[] args) throws IOException { 

    File source = new File("C:\\Users\\rr\\test\\XYZ.docx");        
    File destination=new File("C:\\Users\\rr\\XYZ.docx");
    FileUtils.copyFile(source,destination);
    // copy from folder 'test' to folder 'rr'

   SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH-mm-ss");
   String ts=sdf.format(source.lastModified());
    String outFileName = destination.getName() + ts ;
    //appending ts to the file name
    System.out.println(" new file name is "+outFileName);

      }

我可以將文件從文件夾test復制到文件夾rr,但文件名保持不變。 如何將新文件名更改為oldFileName + timeStamp?

關於什么:

public static void main(String[] args) throws IOException { 
    File source = new File("C:\\Users\\rr\\test\\XYZ.docx");    
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH-mm-ss");
    String ts=sdf.format(source.lastModified());
    File destination=new File("C:\\Users\\rr\\XYZ"+ts+".docx");
    FileUtils.copyFile(source,destination);
    System.out.println(" new file name is "+outFileName);
}

首先創建文件的新名稱,然后將其復制...

別忘了,您需要將名稱和擴展名分開,以便可以在它們之間插入時間戳記...

File source = new File("C:\\Users\\rr\\test\\XYZ.docx");

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH-mm-ss");
String ts = sdf.format(source.lastModified());
String name = source.getName();
String ext = name.substring(name.lastIndexOf("."));
name = name.substring(0, name.lastIndexOf("."));
String outFileName = name + " " + ts + ext;
//appending ts to the file name
System.out.println(" new file name is " + outFileName);

File destination = new File("C:\\Users\\rr", outFileName);

例如,這將在C:\\Users\\rr創建一個名為XYZ 01-01-1970 10-00-00.docx (我沒有原始文件,所以日期為0

暫無
暫無

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

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