File java的文件重命名

红太狼 2022-08-21 09:45 297阅读 0赞

当新文件名已经存在时可以选择删除它

  1. /** *//**文件重命名
  2. * @param path 文件目录
  3. * @param oldname 原来的文件名
  4. * @param newname 新文件名
  5. */
  6. public void renameFile(String path,String oldname,String newname)...{
  7. if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
  8. File oldfile=new File(path+"/"+oldname);
  9. File newfile=new File(path+"/"+newname);
  10. if(!oldfile.exists()){
  11. return;//重命名文件不存在
  12. }
  13. if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
  14. System.out.println(newname+"已经存在!");
  15. else{
  16. oldfile.renameTo(newfile);
  17. }
  18. }else{
  19. System.out.println("新文件名和旧文件名相同...");
  20. }
  21. }

发表评论

表情:
评论列表 (有 0 条评论,297人围观)

还没有评论,来说两句吧...

相关阅读