简体   繁体   中英

Java functions delete() and renameTo() not deleting nor renaming

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

I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?

Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM