2016-03-02 121 views
0

我编程的基本记事本program.This程序的现有文件中包含重命名方法。如果用户将“重命名”写入扫描仪。程序正在根据重命名堆栈等输入更改笔记名称。但是,如果用户输入两个新的notename。 PROGRAMM将错误,如“重命名无效的音符名称,它包含了'。进入一个字”。如果新笔记名称与现有文件名称相同。程序将打印“文件已存在”。我该怎么办?重命名在Java

-rename栈
输入新的音符名称?
堆在
无效注名重命名。它包含了'。进入一个字
-rename栈
输入新的音符名称?
超过
文件已经存在

enter code here 
      else if (noteNameSplited[0].equals("rename")) { 

      File file = new File(noteNameSplited[1]+".ncat"); 

      if(!file.exists()) { 
       System.out.println("File does not exist !"); 
      } 
      else { 
       System.out.println("Enter the new note name"); 
       String data=scan.nextLine(); 
       File file2 = new File(data+".ncat"); 
       file.renameTo(file2); 
      } 
     } 
+0

阅读'Files'类的文档。 – RealSkeptic

回答

0

这可能会帮助您:

https://github.com/openstreetmap/osmosis/blob/master/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/util/AtomicFileCreator.java#L50

if (!tmpFile.exists()) { 
     throw new OsmosisRuntimeException("Can't rename non-existent file " + tmpFile + "."); 
    } 

    // Delete the existing file if it exists. 
    if (file.exists()) { 
     if (!file.delete()) { 
      throw new OsmosisRuntimeException("Unable to delete file " + file + "."); 
     } 
    } 

    // Rename the new file to the existing file. 
    if (!tmpFile.renameTo(file)) { 
     throw new OsmosisRuntimeException(
       "Unable to rename file " + tmpFile + " to " + file + "."); 
    }