我还是 java 新手,不能完全理解 BufferedReader 和 FileWriter 是如何真正工作的,所以上传了其中的一些。这段代码必须删除用户想要的一行,而不是一行。它会删除整个文件内容
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter student number:");
title = titlerem.next ();
System.out.print("Are you sure you want to delete it [Y/N]?");
String tString = titlerem.next();
char temp2 = tString.charAt(0);
switch(temp2)
{
case('Y'):
{
// construct temporary file
File inputFile = new File("phonebook.txt");
File tempFile = new File(inputFile + " ");
BufferedReader br = new BufferedReader (new FileReader("phonebook.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
while((line = br.readLine()) !=null) {
if(line.trim().startsWith(title)){
continue;
}
else{
Pwr.println(line);
Pwr.flush();
}
}
// delete book file before renaming temp
inputFile.delete();
// close readers and writers
Pwr.close();
br.close();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Deletion succesful");
}
else
{
System.out.println("Update failed");
}
}
case('N'):
{
System.out.print("Deletion did not proceed");
break;
}
}
有谁能够帮我。