我的任務是編寫一個程序,將現有文件複製到一個新文件中。程序提示用戶輸入現有文件的名稱,然後詢問新文件的名稱(創建現有文件的副本)。創建新文件 - 異常選項?
如果該文件已經存在,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");
}
你能告訴我爲什麼我沒有得到例外嗎?謝謝。
與'new File()'相同。它不會拋出'FileNotFoundException'。國際海事組織使用例外功能是糟糕的設計'如果'語句更好。例如,應該使用'File#exists()'。 – 4castle
@ 4castle:但是'Scanner'會拋出異常。 – Thilo
明白了,謝謝。 – Steve