How to append data to a file?
Asked Answered
S

4

4

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?

Southeasterly answered 17/5, 2011 at 7:44 Comment(0)
C
8

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

pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
Clark answered 17/5, 2011 at 7:55 Comment(0)
O
3

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

FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);
Opinicus answered 17/5, 2011 at 7:48 Comment(0)
B
3

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

boolean append = true;
pw = new PrintWriter(new FileWriter(new File("filepath.txt"), append));
Battery answered 17/5, 2011 at 7:55 Comment(0)
S
1

In Java 7,

Files.write(FileSystems.getDefault().getPath(targetDir,fileName),
strContent.getBytes(),StandardOpenOption.CREATE,StandardOpenOption.APPEND);
Sparerib answered 13/11, 2013 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.