
本文介绍了写入文件而不删除旧数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在java中写一个文件而不清除(删除)旧的数据在这个文件!
我运行这个代码,看到.txt文件上的所有旧数据在每次运行后都被清除了!
我的代码在这里:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String [] args){
try {
String content =This是写入文件的内容;
档案档案=新档案(/ users / mkyong / filename.txt);
// if file doesnt exists,then create it
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println(完成);
$ b $ catch(IOException e){
e.printStackTrace();
$ div class =h2_lin>解决方案
使用构造函数可以指示文件以追加模式打开:
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
// ^^^^表示追加
I want to write a file in java without cleaning(deleting) older data at that file!
I run this code and see that all older data on .txt file was cleaned after every Run!
my code is here:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/users/mkyong/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
解决方案
Use constructor FileWriter(String filename, boolean append)
that can instruct the file to be opened in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
//^^^^ means append
这篇关于写入文件而不删除旧数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!