gpt4 book ai didi

Java - 无法使用 File .delete() 删除文件

转载 作者:行者123 更新时间:2023-12-02 02:09:39 25 4
gpt4 key购买 nike

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

唯一的问题是,无论我做什么,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

最佳答案

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

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

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

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

关于Java - 无法使用 File .delete() 删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50209712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com