如何将数据追加到文件



我试图写入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();
                }
            }
        }
}

你可以帮我吗?

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

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

使用带有第二个参数"true"的文件编写器和 BufferedWriter:

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

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

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

在Java 7中,

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

相关内容

  • 没有找到相关文章

最新更新