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?
You have to set the Stream to append mode like this:
pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
                        Use a FileWriter with second argument 'true' and a BufferedWriter:
FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With