Im的內容仍然在java中新並不能完全理解的BufferedReader和FileWriter的到底是如何工作等等一些這種被uploaded.This代碼必須刪除用戶想要的線但是而不是一條線..它刪除整個文件內容我刪除特定線功能刪除整個文件
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;
}
}
任何人都可以幫助我。
File.delete()將刪除整個文件,而不是線是偉大的。文檔中說的很多,你的代碼評論似乎反映了這種意圖。 http://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete() – ardent