我不想追加也不想截断现有数据。我想覆盖现有数据。例如,以下代码使 test.txt 文件包含“hello”,但我希望该文件包含“hello6789”。
try(
FileWriter fw = new FileWriter("test.txt"); ){
fw.write("123456789");
}
try(
FileWriter fw = new FileWriter("test.txt"); ){
fw.write("hello");
}
Run Code Online (Sandbox Code Playgroud)
是否可以?
我建议使用Java 7 中添加的NIO.2。
(请注意,下面的代码也使用了try-with-resources。)
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Proj2 {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE)) {
bw.write("123456789");
}
catch (IOException xIo) {
xIo.printStackTrace();
}
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE)) {
bw.write("hello");
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行上述代码后文件test.txt的内容:
hello6789
Run Code Online (Sandbox Code Playgroud)
另请参阅javadoc以获取 [enum] StandardOpenOption。