File.delete() & File.renameTo() 在项目环境中不起作用



我正在尝试创建一个身份验证系统,该系统使用名为Users.dat的文件来存储用户数据。目前,我正在开发一种方法来删除用户,方法是重写users.dat文件,省略指定的用户。下面的代码在一个基本环境中工作,该环境包含一个包罗万象的目录,其中包含位于同一位置的.java文件和Users.dat文件。旧的Users.dat文件被删除,Users.dat.tmp被重命名为User.dat。(这里没有问题,一切正常(。

public static boolean RemoveUser(String userName) {
// TODO remove username from Users.dat
try {
File originalFile = new File("Users.dat");
System.out.println(originalFile.getAbsolutePath());
BufferedReader read = new BufferedReader(new FileReader("Users.dat"));
String line = null;
while ((line = read.readLine()) != null) {
if (line.indexOf(userName) != -1) {
break;
}
}
String[] userInfo = line.split(", ");
if (!userName.equals(userInfo[2])) {
System.out.println("Username not found. No users removed.");
read.close();
return false;
}
File tempFile = new File(originalFile.getAbsolutePath() + ".tmp");
PrintWriter print = new PrintWriter(new FileWriter(tempFile));
String lineToRemove = line;
BufferedReader read2 = new BufferedReader(new FileReader("Users.dat"));
while ((line = read2.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
print.println(line);
print.flush();
}
}
print.close();
read.close();
read2.close();
System.out.println(originalFile.getAbsolutePath());
originalFile.delete(); //This line is not executing correctly
tempFile.renameTo(originalFile); //Nor is this line
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return true;
}

Users.dat文件格式:

Joe, Last, jlast, 58c536ed8facc2c2a293a18a48e3e120, true
Sam, sone, samsone, 2c2a293a18a48e3e12058c536ed8facc, false
Jane, Best, jbest, 293a18a48e3e12052058c536ed8facc2c, false
Andrew, Estes, Aestes, 63a490d69aa544fd1272a976014ad570, true
Test, User, tuser, 63a490d69aa544fd1272a976014ad570, true

我有两个System.out.println(originalFile.getAbsolutePath(((语句,一个在开头,另一个在结尾,以确保路径在处理所有事情的过程中不会以某种方式出错。

正如我所说,该代码是有效的,但是,当我试图在我的项目中实现它时,它会创建Users.dat.tmp并向其写入正确的数据,但它不会删除旧的Users.dat文件,也不会重命名Users.dat.tmp文件以替换Users.dat。我确信目录是正确的,因为我在代码执行时确实会显示它。我想不出originalFile.delete((和tempFile.renameTo(originalFile(不能正常工作的其他原因。

EDIT:使用java.nio.file,我能够生成一条错误消息。上面写着:

java.nio.file.FileSystemException: C:PathUsers.dat: The process cannot access the file because it is being used by another process.

当显示此错误消息时,我没有打开文件,并且在开头提到的测试环境中使用java.nio也没有得到此错误。我不确定这条消息指的是其他什么过程。

第2版:我试着在其他机器上运行代码,一台是Mac,另一台是Windows笔记本电脑,代码在Mac上运行得很好,但我在Windows笔记本电脑上仍然看到同样的问题。

我也遇到了类似的问题。我的问题是没有关闭我读写到文件中的所有流。感谢您的编辑#1,这很有帮助当你包裹BufferedReader read = new BufferedReader(new FileReader("Users.dat"));你不需要关闭内心的读者吗?如果不是为了作者,而是为了那些在这个问题上结结巴巴的人(比如我(,希望这个建议对有用

我之前在main中调用了一个访问Users.dat的函数,但我从未关闭该函数中的BufferredReader。

最新更新