2015-12-02 119 views
1

我想將文檔從一個文件夾複製到另一個文件夾。在新文件夾中,文件名應該是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); 

     } 

我能夠將文件從文件夾中測試複製到文件夾RR但文件名保持不變。我怎樣才能將這個新的文件名更改爲oldFileName + timeStamp?

回答

0

開始首先創建該文件的新名稱,然後將它複製...

不要忘記,你需要將名和擴展名分開,因此你可以插入時間戳之間...

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

+0

謝謝!這工作! –

1

什麼:

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); 
} 
+0

在...... +「。docx」)中拋出語法錯誤; –

+0

看不到什麼可能是錯的 – pedrofurla

相關問題