Steve Steve - 6 months ago 21
Java Question

Create new file - exception options?

My assignment is to write a program that copies an existing file into a new file. The program prompts the user for the name of the existing file and then asks for the name of the new file (to create a copy of existing).

If the file already exists, 3 options should be presented:
1. Exit the program
2. Overwrite the existing file
3. Enter a new name for the file

In my project folder, I have two files old.txt and new.txt. When I enter them, it does not state the file already exists, it simply just overwrites the existing new.txt. Here is my code:

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");
}


Can you tell me why I am not getting an exception? Thanks.

Answer

According to JavaDoc, File#createNewFile does not throw an exception but just returns false.

If you are on a recent Java version, you should use Files#createFile instead (which will throw the exception). The new Files/Path API is a cleaned-up version for doing file I/O (the legacy one has to be kept for compatibility).

Comments