gpt4 book ai didi

java - 删除文本文件上的行

转载 作者:行者123 更新时间:2023-11-30 03:13:50 24 4
gpt4 key购买 nike

我尝试使用此代码删除文本文件的某些行。但是,当我删除旧文件并将其替换为新文件时。该文件不会被删除也不会被重命名。谁能帮我解决这个问题吗? PS:我尝试了所有能找到的方法,但都行不通我的注册系统项目需要它。提前致谢

public static void deleteStudents() throws IOException, FileNotFoundException
{
Scanner console = new Scanner(System.in);
String SY, date;
System.out.println("ENTER THE SCHOOL YEAR: SY: ");
SY = console.next();

int i = 0;

Scanner print = new Scanner(new FileReader("Students- SY " + SY + " " + ".txt"));
//display text file
while(print.hasNextLine())
{
String stud= print.nextLine();
System.out.println(stud);
}

File inputFile = new File("Students- SY " + SY + " " + ".txt");
File tempFile = new File("Students- SY " + SY + " " + ".txt.bak");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String remove;
String currentLine;

System.out.println("ENTER STUDENT's ID NUMBER TO BE DELETED: ");
remove = console.next();
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(remove))
{
writer.write(String.format("%s%n",currentLine));

}
}
//close reader/writer
writer.close();
reader.close();
//delete file
if(inputFile.delete())
{
tempFile.renameTo(inputFile);
}
else
{
System.out.println("FAIL");
}

最佳答案

您没有正确处理流。当您尝试删除/重命名文件时,由于 print 变量中保存的 FileReader/Scanner ,该文件仍由 Java 打开还开着。这将防止文件在 Windows 上被删除。

您需要将从文件中读取的内容包装在 try block 中,并在 finally 中调用 print.close() ,或使用 try-with-resources

另外,不要忘记以相同的方式关闭readerwriter(在finally中或使用try-with -资源)。

关于java - 删除文本文件上的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33080216/

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