[英]When deleting data from a file, temp file won't rename back to original file
I am trying to remove a line based on user input. 我试图根据用户输入删除一行。 myFile.txt looks like:
myFile.txt看起来像:
Matt
Brian
John
However when I enter "Brian" (to remove this line), It is deleted on the temp file (myTempFile.txt), but not renamed back to the original file (myFile). 但是,当我输入“ Brian”(以删除此行)时,它会在临时文件(myTempFile.txt)上删除,但不会重命名回原始文件(myFile)。 Why is this?
为什么是这样? Thanks
谢谢
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();
}
}
Your original file is open that's why it's not working. 您的原始文件已打开,这就是为什么它不起作用的原因。
I suggest to do the renameTo(...)
after the while and put a reader.close();
我建议过一会儿再做一个
renameTo(...)
,然后放置一个reader.close();
before it. 在它之前。 It makes no sense to rename it at each
readLine()
of your original file. 在原始文件的每个
readLine()
上重命名都是没有意义的。 Do the processing, then rename the temporary file. 进行处理,然后重命名临时文件。
Like: 喜欢:
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
}
reader.close();
writer.close();
inputFile.delete(); //Added to my original post.
tempFile.renameTo(inputFile);
See as example: http://www.tutorialspoint.com/java/io/file_renameto.htm 参见示例: http : //www.tutorialspoint.com/java/io/file_renameto.htm
After some research, I saw this: http://www.coderanch.com/t/595269/java-io/java/doesn-File-renameTo-work . 经过一番研究,我看到了这一点: http : //www.coderanch.com/t/595269/java-io/java/doesn-File-renameTo-work 。 If the file does exist, the renaming will not work.
如果该文件确实存在,则重命名将不起作用。 Try to Delete the inputFile before renaming.
重命名之前,请尝试删除inputFile。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.