简体   繁体   English

在Java中重命名文件

[英]Renaming the file in java

File file= new File("C:\\Documents and Settings\\Administrator\\Desktop\\ajay\\abc.csv");
Timestamp ts=new Timestamp(new Date().getTime());
String str= ts.toString();
String st="C:\\Documents and Settings\\Administrator\\Desktop\\ajay\\abc\\"+str+".csv";
System.out.println(new Date().getTime());
boolean b=file.renameTo(new File(st));
System.out.println(b);

In this code snippet I try to rename the file but I'm unable to find the error in it. 在此代码段中,我尝试重命名该文件,但无法在其中找到错误。

Won't getTime().toString() return a string with colons in it? getTime().toString()返回带有冒号的字符串? That would be illegal in a filename. 这在文件名中是非法的。

you can remove colon from String for example with this method : 您可以使用以下方法例如从String中删除冒号:

      String time = "12:12:12";
      String time2 = time.replace(":", "");

output be : 121212 输出为:121212

I would use something like 我会用类似的东西

final File file= new File("C:\\Documents and Settings\\Administrator\\Desktop\\ajay\\abc.csv");
final Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
final StringBuilder str = new StringBuilder();
str.append(cal.get(Calendar.YEAR));
str.append(cal.get(Calendar.MONTH));
str.append(cal.get(Calendar.DATE));
final String st="C:\\Documents and Settings\\Administrator\\Desktop\\ajay\\abc"+str+".csv";
System.out.println(new Date().getTime());
final boolean b = file.renameTo(new File(st));
System.out.println(b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM