如何重命名文件名而不改变其类型?
我对重命名 java 文件有疑问...我的应用程序必须重命名传入的文件,即 mdb、dbf、xls、xml 等。 格式。 我使用了以下源代码。
例如:
String filename = "D:/sample.mdb";
File filediriden = new File(filename);
String[] filetype = filename.split("\\.");
System.out.println("Filetype :"+filetype[1]);
String newfilename = "D:/new."+filetype[1];
File newfilediriden = new File(newfilename);
System.out.println("New File Name "+newfilename);
boolean rename = filediriden.renameTo(newfilediriden);
if(rename)
System.out.println("File Renamed");
if(filediriden.isFile()){
System.out.println("filename" + filediriden.getName());
}else{
System.out.println("not a filename");
}
OUTPUT:
Filetype : mdb
New File Name D:/new.mdb
File Renamed
not a filename
之后我检查了它是否是一个文件,但它没有进入那个...请帮助...
I have doubt in renaming java files... My application has to rename the incoming file which is mdb,dbf,xls,xml,etc. format. I used the following source code.
eg:
String filename = "D:/sample.mdb";
File filediriden = new File(filename);
String[] filetype = filename.split("\\.");
System.out.println("Filetype :"+filetype[1]);
String newfilename = "D:/new."+filetype[1];
File newfilediriden = new File(newfilename);
System.out.println("New File Name "+newfilename);
boolean rename = filediriden.renameTo(newfilediriden);
if(rename)
System.out.println("File Renamed");
if(filediriden.isFile()){
System.out.println("filename" + filediriden.getName());
}else{
System.out.println("not a filename");
}
OUTPUT:
Filetype : mdb
New File Name D:/new.mdb
File Renamed
not a filename
After that I checked whether its a file or not but its not going into that...Help plz...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重命名文件后,旧的 File 对象 (filediriden) 仍指向不再存在的旧名称。 您想要使用新的 File 对象 (newfilediriden) 进行检查。
另外,可能存在包含多个点的文件,因此也许 filetype[filetype.length-1] 更安全。
After you rename the file, the old File object (filediriden) still points to the old name, which no longer exists. You want to check using the new File object (newfilediriden).
Also, there could be files with more than one dot in them, so maybe filetype[filetype.length-1] is safer.
问题是您正在检查 filedirden 而不是 newfiledirden。
在测试时,filedirden 不再存在,因为它指向的文件已重命名。
The problem is you're checking the filedirden instead of newfiledirden.
At the point of test, filedirden doesn't exist anymore, as the file it points to was renamed.