【问题标题】:Java - Can't delete file using File .delete()Java - 无法使用 File .delete() 删除文件
【发布时间】:2018-10-16 23:52:19
【问题描述】:

所以我使用以下代码基本上从文件中删除一行,方法是编写一个包含除该行之外的所有内容的临时文件,然后删除旧文件并将新文件名设置为旧文件名。

唯一的问题是无论我做什么,delete() 方法和 renameTo() 方法都返回 false

我在这里查看了大约 20 个不同的问题,但他们的解决方案似乎都没有帮助。这是我正在使用的方法:

public void deleteAccount(String filePath, String removeID)
{

    String tempFile = "temp.csv";
    File oldFile = new File(filePath);
    File newFile = new File(tempFile);

    String firstname = "";
    String lastname = "";
    String id = "";
    String phonenum = "";
    String username = "";
    String password = "";
    String accounttype = "";

    try
    {
        FileWriter fw = new FileWriter(newFile, true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);

        Scanner reader = new Scanner(new File(filePath));
        reader.useDelimiter("[,\n]");

        while (reader.hasNext())
        {
            firstname = reader.next();
            lastname = reader.next();
            id = reader.next();
            phonenum = reader.next();
            username = reader.next();
            password = reader.next();
            accounttype = reader.next();
            if (!id.equals(removeID))
            {
                pw.println(firstname + "," + lastname + "," + id + "," + phonenum + "," + username + "," + password
                        + "," + accounttype + ",");
            }
        }
        reader.close();
        pw.flush();
        pw.close();


        oldFile.delete();
        System.out.println(oldFile.delete());
        File dump = new File(filePath);
        newFile.renameTo(dump);
        System.out.println(newFile.renameTo(dump));
    } catch (Exception e)
    {

    }

}

被解析到filePath 字符串中的字符串是"login.csv",它在之前的方法中被读取,但读取器肯定会被关闭。

编辑:这就是 login.csv 的样子。

John,Doe,A1,0123456789,johnd,password1,Admin
Jane,Doe,A2,1234567890,janed,password2,CourseCoordinator
John,Smith,A3,2345678901,johns,password3,Approver
Jane,Smith,A4,356789012,johns,password4,CasualStaff
Josh,Males,A5,0434137872,joshm,password5,Admin

【问题讨论】:

  • 你能从 login.csv 中添加几行吗?
  • 我认为如果您使用 try-with-resources 语法,则问题不会发生,该语法可确保再次正确关闭所有内容,并且如果您将删除/重命名代码放在外面try-catch 块。
  • 在 login.csv 文件中添加了所有内容。我也试试 Dreamspace
  • 尝试删除一个不相关的文件,看看是否有效?
  • 尝试删除该文件,它说它正在被另一个程序使用,但它唯一可能被使用的是 Eclipse 本身

标签: java file csv writer reader


【解决方案1】:

您调用了两次 delete() 方法 - 一次不使用返回值 (oldFile.delete()),第二次打印返回值 (System.out.println(oldFile.delete()))。

第二次调用将始终返回false - 因为两次删除尝试都将因相同原因失败,或者因为第一次会成功(因此第二次将失败,因为文件不再存在)。

你正在寻找的语法是这样的:

boolean deletionResult = oldFile.delete();
System.out.println("Deletion result is " + deletionResult);

【讨论】:

  • 仍然是假的:/
  • 确保文件没有在其他任何地方打开,例如在文本编辑器中。
猜你喜欢
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 2017-08-30
相关资源
最近更新 更多