How to append data to a file?

2019-01-08 00:59发布

问题:

I trying to write into the txt file.
But with out losing the data that is already stored in the file.

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.

My code is:

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

        }

}

Can you help me?

回答1:

You have to set the Stream to append mode like this:

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


回答2:

Create a separate variable to emphasize that, appending to file.

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


回答3:

Use a FileWriter with second argument 'true' and a BufferedWriter:

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


回答4:

In Java 7,

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