0 java io overwrite filewriter
这是我目前的代码:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
}
public void Write(String content) {
BufferedWriter bw = null;
try {
//Specify the file name and path here
File file = new File("C:\\Users\\Gbruiker\\Dropbox\\Java\\Rekenen\\src\\sommen.txt");
/* This logic will make sure that the file
* gets created if it is not present at the
* specified location*/
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.append(content);
bw.append("\n");
System.out.println("File written Successfully");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
}
catch (Exception ex) {
System.out.println("Error in closing the BufferedWriter" + ex);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何使它不会覆盖文本文件中的当前文本?
有什么建议?我是以正确的方式做到的吗?程序必须向文件添加一些文本,但不能覆盖当前内容.因为现在它正在覆盖当前内容.