2016-05-17 42 views
0

我的任務是編寫一個程序,將現有文件複製到一個新文件中。程序提示用戶輸入現有文件的名稱,然後詢問新文件的名稱(創建現有文件的副本)。創建新文件 - 異常選項?

如果該文件已經存在,3個選項應提交:1。 退出程序 2.覆蓋現有文件 3.輸入該文件的新名稱

在我的項目文件夾中,我有兩個文件old.txt和new.txt。當我輸入它們時,它並不表示文件已經存在,它只是覆蓋現有的new.txt。這裏是我的代碼:

existingFile = JOptionPane.showInputDialog("Enter the name of the " 
     + "existing file: "); 

    try 
    { 
     file = new File(existingFile); 
     inputFile1 = new Scanner(file); 
    } 
    catch (FileNotFoundException e) 
    { 
     JOptionPane.showMessageDialog(null, existingFile + 
       " does not exist. Exiting program."); 
     System.exit(0); 
    } 

    newFile = JOptionPane.showInputDialog("Enter the name of the " 
      + "new file: "); 
    try 
    { 
     file2 = new File(newFile); 
     createFile = file2.createNewFile(); 
     JOptionPane.showMessageDialog(null, "Copying " + existingFile + 
       " into " + newFile); 
    } 
    catch (FileAlreadyExistsException e) 
    { 
     JOptionPane.showMessageDialog(null, newFile + " already exists."); 
     System.out.println("Choose from the following choices:"); 
     System.out.println("1. Exit the program"); 
     System.out.println("2. Overwrite the existing file"); 
     System.out.println("3. Enter a new name for the file"); 
    } 
    catch (IOException e){ 
     JOptionPane.showMessageDialog(null, "Something"); 
    } 

你能告訴我爲什麼我沒有得到例外嗎?謝謝。

回答

1

According to JavaDoc,File#createNewFile不會引發異常,只是返回false。

如果您使用的是最近的Java版本,則應該使用Files#createFile(這會引發異常)。新的Files/Path API是用於執行文件I/O的清理版本(爲保持兼容性,舊版本必須保留)。

+0

與'new File()'相同。它不會拋出'FileNotFoundException'。國際海事組織使用例外功能是糟糕的設計'如果'語句更好。例如,應該使用'File#exists()'。 – 4castle

+0

@ 4castle:但是'Scanner'會拋出異常。 – Thilo

+0

明白了,謝謝。 – Steve

0

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile%28%29

CreateNewFile只會拋出:

IOException - If an I/O error occurred 
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file 

將返回:

true if the named file does not exist and was successfully created; false if the named file already exists 

你應該改變你的

catch (FileAlreadyExistsException e) 

if(createFile)