java创建新的文件异常选项?
我的任务是编写一个程序,将现有文件复制到新文件中。程序会提示用户输入现有文件的名称,然后要求输入新文件的名称(以创建现有文件的副本)
如果文件已经存在,则应提供3个选项: 1.退出程序 2.覆盖现有文件 3.输入文件的新名称
在我的项目文件夹中,我有两个旧文件。txt和新的。txt。当我输入它们时,它并不表示文件已经存在,它只是覆盖现有的新文件。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 楼答案
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile%28%29
CreateNewFile只会抛出:
并将返回:
你应该换衣服
到
# 2 楼答案
According to JavaDoc,
File#createNewFile
不抛出异常,只返回false如果您使用的是最新的Java版本,那么应该使用^{} (这将引发异常)。新的
Files
/Path
API是一个用于执行文件I/O的清理版本(为了兼容性,必须保留旧版本)