Java 函数 delete() 和 renameTo() 不删除也不重命名

问题描述

public void newEditSportRecord(){
    String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansprojects\Assignment\
    String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
    
    String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansprojects\Assignment\
    File oldFile = new File(filepath);
    System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansprojects\Assignment\sport.txt
    File newFile = new File(tempFile);
    System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansprojects\Assignment\temp.txt
    String ID,name = "";

    try {
        FileWriter fw = new FileWriter(tempFile,true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);
        x = new Scanner(new File(filepath));
        
        while (x.hasNextLine()) {
            ID = x.next();
            System.out.println(ID);
            name = x.next();
            System.out.println(name);

            if (ID.equals(editTerm)) {
                newID = JOptionPane.showInputDialog("Enter new Sport ID:");
                newName = JOptionPane.showInputDialog("Enter new Sport Name:");
                pw.println(newID);
                pw.println(newName);
                pw.println();
                JOptionPane.showMessageDialog(modifySport,"Record Modified");
            } else {
                pw.println(ID);
                pw.println(name);
                pw.println();
            }
        }
        x.close();
        pw.flush();
        pw.close();
        oldFile.delete();
        File dump = new File(filepath);
        newFile.renameto(dump);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(modifySport,ex);
    }
}

我有以下功能来尝试修改文本文件。但是,它不会删除原始文件“sport.txt”,也不会将“temp.txt”重命名为“sport.txt”。它确实从文件中读取并创建“sport.txt”的副本,并将所有相关修改作为“temp.txt”。我曾怀疑这是作家的问题,但已关闭所有作家,问题仍然存在。这是否仅仅是因为文件夹存在于本地磁盘上的 Documents 文件夹中的权限问题?

解决方法

是的,这是一个权限问题。要么更改 Documents 文件夹的权限并为您的用户授予所有权限,要么更改您的工作文件夹。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...