将文件从一个文件夹复制到另一个文件夹,并使用旧文件名+时间戳重命名新文件夹中的文件
问题描述:
我想将文档从一个文件夹复制到另一个文件夹。在新文件夹中,文件名应该是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?
答
开始首先创建该文件的新名称,然后将它复制...
不要忘记,你需要将名和扩展名分开,因此你可以插入时间戳之间...
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
)
答
什么:
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
谢谢!这工作! –