【问题标题】:Rename a File if exists重命名文件(如果存在)
【发布时间】:2012-10-04 04:34:53
【问题描述】:

当我尝试使用已存在的文件名保存文件时,我需要提示用户重命名文件才能保存。提示用户将文件重命名为目录中存在相同文件的更好方法是什么?我需要通过我用来保存文件的同一个对话框来实现这一点。

File exportFile = new File(FilePath + "\\"+ FileName);
boolean exists = exportFile.exists();  

if (!exists) {  

    System.out.println("File does not exists");  
    // TODO code here             
}
else{  

    System.out.println( "File exists.");
    // TODO code here                                       
}

代码将在 //TODO 部分实现。我该怎么做?

【问题讨论】:

    标签: java eclipse dialog


    【解决方案1】:

    while(exists) { \\Prompt the user to enter another name & change "exists" status correspondingly}

                while(exists) 
            {
             String temp=dis.readLine();
             exists = (FilePath + "\\"+ temp).exists();
             if(!exists) {exportFile = new File(FilePath + "\\"+ temp); break;}
    
              }  
    

    其中 dis 是一个 DataInputStream 对象。祝你好运。

    【讨论】:

      【解决方案2】:

      你可以这样做,

          File f = new File("C:\\Users\\jayesh.patel\\Desktop\\mdn.txt");
          if(f.exists()){
              boolean renameResult = f.renameTo(new File("C:\\Users\\jayesh.patel\\Desktop\\mdn1.txt"));
              if(renameResult){
                  System.out.println("Rename Success");
              }else{
                  System.out.println("Rename Failed");
              }
          }else{
              System.out.println("File Not Exist");
          }
      

      【讨论】:

        【解决方案3】:

        您不应该尝试事后猜测 API。只需尝试重命名文件:如果失败,它仍然处于打开状态 (Windows) 或目标存在。根据rename()结果做出决定,而不是试图预测它会做什么。否则你只是在预测未来,所以在 Knob Hill 租一所大房子,把它连接起来,然后给自己买一块占卜板。

        【讨论】:

          猜你喜欢
          • 2015-03-18
          • 2014-08-09
          • 2012-04-04
          • 2014-07-20
          • 1970-01-01
          • 2015-06-14
          • 2023-04-06
          • 2020-09-17
          相关资源
          最近更新 更多