如何在java中覆盖文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20089220/
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 overwrite a file in java
提问by user3002538
In my program, I am trying to read the file and then trying to overwrite the file using txtFile method. f is the file which I am reading and doing operations on its contents and now want to replace its contents with the new string, s.
在我的程序中,我试图读取文件,然后尝试使用 txtFile 方法覆盖文件。f 是我正在读取并对其内容进行操作的文件,现在想用新字符串 s 替换其内容。
String s = obj1.method(string);
toFile(s, f);
my txtFile method is below:
我的 txtFile 方法如下:
public static void txtFile(String cnvrt, File file)
{
try
{
PrintWriter printWriter = new PrintWriter (file);
printWriter.print(cnvrt);
printWriter.close ();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
While doing this way, my original content is erased and the file gets empty. Please suggest me how to overwrite the same file using printWriter class? Even when I am using the FileWriter
and BufferedReader
, I obtained the empty file. Can somebody explain me this behavior?
这样做时,我的原始内容被删除并且文件变空。请建议我如何使用 printWriter 类覆盖同一个文件?即使我使用FileWriter
and BufferedReader
,我也获得了空文件。有人可以解释我这种行为吗?
采纳答案by Scary Wombat
Based upon your code and the API, it should work (OP wants to replace the contents).
根据您的代码和 API,它应该可以工作(OP 想要替换内容)。
see http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.File)
见http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.File)
file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
file - 用作此编写器目标的文件。如果文件存在,那么它将被截断为零大小;否则,将创建一个新文件。输出将被写入文件并被缓冲。
Update
更新
Before calling PrintWriter printWriter = new PrintWriter (file);
you should maybe to close the file first to ensure that there are no locks on the file.
在调用之前,PrintWriter printWriter = new PrintWriter (file);
您应该先关闭文件以确保文件上没有锁定。
Furthermore, unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.
此外,与 PrintStream 类不同,如果启用自动刷新,则仅在调用 println、printf 或 format 方法之一时才会执行,而不是在碰巧输出换行符时执行。
So use printWriter.flush()
to ensure the contents are flushed to disk.
因此使用printWriter.flush()
以确保将内容刷新到磁盘。
Of course you should check to make sure that the contents that you are writing in valid and not null.
当然,您应该检查以确保您正在写入的内容有效且不为空。
回答by Aniket Thakur
Why not simply delete and create new?
为什么不简单地删除并创建新的?
public static void txtFile(String cnvrt, File file)
{
PrintWriter printWriter = null;
String filepath = file.getAbsolutePath();
try {
if(file.exists()){
file.delete();
}
printWriter = new PrintWriter(new File(filepath));
printWriter.print(cnvrt);
printWriter.close ();
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
Note : It is not a good programming practice to catch RuntimeException unless you intent to do something with it.
注意:除非您打算对其进行处理,否则捕获 RuntimeException 不是一个好的编程习惯。
回答by Paul Samsotha
There's two ways I can think of if you want to overwrite the file with changed/altered/updated information in the file
如果您想用文件中已更改/更改/更新的信息覆盖文件,我可以想到两种方法
1) Use a StringBuilder
to append each desired/changed line, then print the StringBuilder#toString()
to the file. This overwrite the file with updated info
1) 使用 aStringBuilder
附加每个所需/更改的行,然后将其打印StringBuilder#toString()
到文件中。这会用更新的信息覆盖文件
2) Write each desired/changed line to a temp file, then rename the temp file back to the old file name. See this Answer
2)将每个所需/更改的行写入临时文件,然后将临时文件重命名回旧文件名。看到这个答案