I have a system that writes a csv file. If the filename the user inputs already exists, then it asks if they would like to override it or rename it. If they choose to override it, the system works fine. However, when they choose to rename it, they get an error because the file object's canWrite()
method returns false
.
String saveName = scanner.next();
File csvFile = Paths.get(saveName + ".csv").toFile();
while (csvFile.exists()) {
char answer = scanner.next().charAt(0);
if (answer == 'y') {
scanner.close();
break;
}
else if (answer == 'n') {
scanner.close();
throw new IllegalArgumentException("Error: Rerun program with unique filename.");
}
else if (answer == 'r') {
String response = scanner.next();
csvFile = Paths.get(response + ".csv").toFile();
}
}
if (!csvFile.canWrite()) {
scanner.close();
throw new IOException("Error: " + csvFile.getPath() + " is not writable.");
}
Any time the program gets into the final else-if
in the while
loop, it changes csvFile
to another value, and then becomes unwritable. It works fine if I never get to that else-if
statement and csvFile
stays the same as the initial declaration before the while
loop.