我想重写文件的内容。
到目前为止我想到的是这样的:
- 保存文件名
- 删除现有文件
- 新建一个同名的空文件
- 将所需内容写入空文件
这是最好的方法吗?或者有没有更直接的方式,即不用删除和创建文件,只需更改内容?
用 FileOutputStream 覆盖文件 foo.log:
File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
// false to overwrite.
byte[] myBytes = "New Contents\n".getBytes();
fooStream.write(myBytes);
fooStream.close();
或使用 FileWriter :
File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
// false to overwrite.
fooWriter.write("New Contents\n");
fooWriter.close();
我强烈建议为此使用 Apache Common 的 FileUtil。我发现这个包非常宝贵。它易于使用,同样重要的是,当您稍后返回时,它很容易阅读/理解。
//Create some files here
File sourceFile = new File("pathToYourFile");
File fileToCopy = new File("copyPath");
//Sample content
org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content");
//Now copy from source to copy, the delete source.
org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy);
org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);
更多信息请访问: http ://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
您需要以读写方式打开文件,因此:
RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw");
String tmp;
while (tmp = raf.readLine() != null) {
// Store String data
}
// do some string conversion
raf.seek(0);
raf.writeChars("newString");
除非您只是在最后添加内容,否则这样做是合理的。如果要追加,请使用追加构造函数尝试FileWriter 。
稍微好一点的顺序是:
不幸的是,renameTo不能保证进行原子重命名。
在下面的示例中,“false”会导致文件被覆盖,true 会导致相反的结果。
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();
有时可能希望保留一个巨大的空文件,以避免操作系统根据需要分配空间的额外成本。这通常由数据库、虚拟机以及在处理和写入批量数据的批处理程序中完成。这将显着提高应用程序的性能。在这些情况下,编写一个新文件并重命名它并没有真正的帮助。相反,必须填充空文件。那是必须进入覆盖模式的时候。
java.nio.file.Files
由于 Java 7 和新的文件 API,使用该类非常简单:
Files.write(Path.of("foo.log"), "content".getBytes(StandardCharsets.UTF_8));
Java 8 中用于编写 UTF-8 字符串列表的新功能:
Files.write(Path.of("foo.log"), List.of("content line 1", "content line 2"));
Java 11 中用于编写 UTF-8 字符串的新功能:
Files.writeString(Path.of("foo.log"), "content");
Guava Files.write “用字节数组的内容覆盖文件”:
Files.write(bytes, new File(path));