创建新文件 - 例外选项?

时间:2016-05-17 02:06:53

标签: java exception

我的任务是编写一个程序,将现有文件复制到一个新文件中。程序提示用户输入现有文件的名称,然后询问新文件的名称(以创建现有文件的副本)。

如果文件已存在,则应显示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");
    }

你能告诉我为什么我没有得到例外吗?感谢。

2 个答案:

答案 0 :(得分:1)

According to JavaDocFile#createNewFile不会抛出异常,只会返回false。

如果您使用的是最新的Java版本,则应使用Files#createFile代替(这将引发异常)。新的Files / Path API是用于执行文件I / O的已清理版本(为保持兼容性,必须保留旧版本。)

答案 1 :(得分: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)