如何在java中删除文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19886904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete a text file in java?
提问by user2350622
I want to overwrite to a text file using java by first create a new file and then delete the old one and finally rename the file I just created with the same name of my old file. But my code does not work.
我想使用 java 覆盖一个文本文件,首先创建一个新文件,然后删除旧文件,最后用与旧文件相同的名称重命名刚刚创建的文件。但是我的代码不起作用。
File oldFile = new File("charList.txt");
File newFile = new File("new.txt");
oldFile.deleteOnExit();
if(oldFile.delete()){
newFile.renameTo(oldFile);
}
回答by Stephen C
On some platforms (e.g. Windows!), you cannot delete a file that the current program or another one has open. I expect that is what is causing the delete step in your program to fail ... if that is what is actually happening.
在某些平台上(例如 Windows!),您无法删除当前程序或其他程序已打开的文件。我希望这就是导致程序中的删除步骤失败的原因......如果这是实际发生的事情。
As @Matt Ball's comment points out, it might be the rename that is failing ... because in the code you showed us, you are actually renaming "new.txt" to itself!
正如@Matt Ball 的评论指出的那样,可能是重命名失败了……因为在您向我们展示的代码中,您实际上是将“new.txt”重命名为自身!
Finally, your oldFile.deleteOnExit()
call is almost certainly incorrect:
最后,你的oldFile.deleteOnExit()
电话几乎肯定是不正确的:
It won't affect the deletion of
oldFile
in the following code ... if that is your intent.If it does succeed, it will (I think!) delete the file that you carefully renamed to "charList.txt". A
File
denotes a file pathname ... not a file handle.
它不会影响
oldFile
以下代码中的删除...如果这是您的意图。如果成功,它会(我认为!)删除您小心重命名为“charList.txt”的文件。A
File
表示文件路径名...不是文件句柄。
回答by Stefan Freitag
- With
deleteOnExit()
you are deleting the oldFile when the virtual machine terminates. I think this is not what you wanted, as you are callingdelete()
on the same file in the next command. Additionally you are renaming your newFile to newFile instead of oldFile. Try
newFile.renameTo(oldFile)
- 随着
deleteOnExit()
在虚拟机终止你删除的oldfile。我认为这不是您想要的,因为您delete()
将在下一个命令中调用同一个文件。 此外,您将 newFile 重命名为 newFile 而不是 oldFile。尝试
newFile.renameTo(oldFile)