如何将数据附加到文件?

时间:2011-05-17 07:44:20

标签: java file file-io

我试着写入txt文件。
但是丢失已经存储在文件中的数据。

但我的问题是,当我将字符串放入txt文件时,新字符串会覆盖我之前放入的旧字符串。

我的代码是:

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();
                }
            }

        }

}

你能帮助我吗?

4 个答案:

答案 0 :(得分:8)

您必须将Stream设置为追加模式,如下所示:

pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));

答案 1 :(得分:3)

创建一个单独的变量来强调它,附加到文件。

boolean append = true;
pw = new PrintWriter(new FileWriter(new File("filepath.txt"), append));

答案 2 :(得分:2)

使用带有第二个参数'true'的FileWriter和一个BufferedWriter:

FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);

答案 3 :(得分:1)

在Java 7中,

Files.write(FileSystems.getDefault().getPath(targetDir,fileName),
strContent.getBytes(),StandardOpenOption.CREATE,StandardOpenOption.APPEND);