如何将数据附加到文件? [英] How to append data to a file?
本文介绍了如何将数据附加到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图写入txt文件。
但是丢失已经存储在文件中的数据。
I trying to write into the txt file.
But with out losing the data that is already stored in the file.
但是我的问题是当我将字符串放在txt文件中时,新的字符串覆盖我放在前面的旧字符串。
But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.
我的代码是:
public void addWorker(Worker worker){
workers.put(worker.getId(), worker);
}
public void printWorker (String id){
Worker work = (Worker) workers.get( id );
if (work == null) {
System.out.println("Worker NOT found");
}
else {
work.printText();
}
}
public void printWorkers() {
if (workers.size() == 0) {
System.out.println("No workres");
return;
}
Collection<Worker> c = workers.values();
Iterator<Worker> itr = c.iterator();
System.out.println("Workers in division "+dName+ ":");
while (itr.hasNext()) {
Worker wo = itr.next();
wo.printText();
}
}
public void writeToFile(){
PrintWriter pw = null;
try{
pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
Collection<Worker> c = workers.values();
Iterator<Worker> itr = c.iterator();
while (itr.hasNext()) {
Worker wo = itr.next();
pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
pw.println();
}
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (pw != null) {
pw.close();
}
}
}
}
你可以帮助我吗?
推荐答案
你必须将Stream设置为附加模式: / p>
You have to set the Stream to append mode like this:
pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
这篇关于如何将数据附加到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文