Java如何删除文件中的一行?
我想用Java删除文件中的一行记录,例如我的文件 studentID studentName studentAddress studentPhoneNo AAA|AAA AAA | AAAAAAAAAAA | AAAAAAAAAAAA BBB|BBB BBB | BBBBBBBBBBB | BBBBBBBBBBBB CCC|CCC CCC | CCCCCCCCCCC | CCCCCCCCCCCCJava如何删除文件中的一行?,java,file,Java,File,我想用Java删除文件中的一行记录,例如我的文件 studentID studentName studentAddress studentPhoneNo AAA|AAA AAA | AAAAAAAAAAA | AAAAAAAAAAAA BBB|BBB BBB | BBBBBBBBBBB | BBBBBBBBBBBB CCC|CCC CCC | CCCCCCCCCCC | CCCCCCCCCCCC 但是我遇到了这个错误,无法删除文件。我刚刚测试了这个程序,它运行得非常好,并产生了预期的结果(在W
但是我遇到了这个错误,无法删除文件。我刚刚测试了这个程序,它运行得非常好,并产生了预期的结果(在Windows上)。 所以问题不在于代码,可能是权限问题 但是正如在评论中所说的,如果您只是假设您的字符串在您的文件中只能作为“学生ID”找到,那么可能(也将)导致bug
正确的方法是读取文件的内容,将其转换为学生列表(学生id为字段的类,以及其他字段,如果需要),删除不需要学生id的类,然后再次保存文件,剩余列表序列化为特定格式。此代码没有问题,您没有从服务器删除该文件的权限。还有一件事是,更改逻辑以查找匹配行。仅针对您不想使用Java的情况:
grep-v BBB yourfile>yournewfile
就是这样:程序无法删除该文件:可能是因为其他人正在使用该文件,或者是因为用户没有删除该文件的权限。哦,您也不希望只检查包含BBB
的字符串,因为该子字符串可能是另一列值的一部分。我正在使用Eclipse运行,我已将文件设置为完全控制,但我仍然遇到相同的问题。我正在使用Eclipse运行,我已将文件设置为完全控制,但我仍然遇到相同的问题。
try {
File inFile = new File(studentFile);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
// Construct the new file that will later be renamed to the original
// filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(studentFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().contains(id)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
// Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}