Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append data to a file?

Tags:

java

file

file-io

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?

like image 386
sergey Avatar asked Dec 10 '22 08:12

sergey


2 Answers

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

pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
like image 194
Jens Avatar answered Dec 11 '22 21:12

Jens


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

FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);
like image 24
abalogh Avatar answered Dec 11 '22 23:12

abalogh