我試圖根據用戶輸入刪除一行。 MYFILE.TXT樣子:當從文件中刪除數據時,臨時文件將不會重命名爲原始文件
Matt
Brian
John
然而,當我進入「布萊恩」(刪除這條線),它是在臨時文件(myTempFile.txt)刪除,但不能更名回原來的文件(MYFILE )。爲什麼是這樣?謝謝
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class testcode {
public static void main(String[] args) throws IOException {
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
Scanner myScan = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
System.out.print("Please enter student first name: ");
String lineToRemove = myScan.nextLine();
String currentLine;
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
tempFile.renameTo(inputFile);
}
writer.close();
reader.close();
myScan.close();
}
}
任何人都可以幫忙嗎? – Adam