java : append data in existing file

2019-07-27 02:18发布

问题:

i have a file DataFile.txt with few records. when i am adding new entry, it clears all the other records and saving only new one. but i want to append that record.

private void saveFile()
      {
        try
        {
            PrintWriter out = new PrintWriter(new FileWriter("DataFile.txt"));


            String name ="";
            String ID="";
            String roomType ="";
            String meal="";
            int days=0;
            int tprice=0;


            for (int i = 0; i < myList.size(); i++)
            {
                Customer c = myList.get(i);

                name = c.getName();
                ID = c.getID();
                roomType = c.getRoomItem();
                meal = c.getMealItem();
                days = c.getDaysIndex();
                tprice = c.getTotalPrice();

                out.println(name + "," + ID+ "," + roomType+ "," + meal+ "," + days+ "," + tprice);
            }
            out.close();
            JOptionPane.showMessageDialog(null,"Data saved successfully!","",
                                                              JOptionPane.INFORMATION_MESSAGE);

          }
          catch (Exception ex)
          {
             System.out.println("save file fail");
          }
      } //end of the method

thanks.

回答1:

You can change to use the FileWriter constructor which takes a boolean append parameter:

PrintWriter out = new PrintWriter(new FileWriter("DataFile.txt", true));

However:

  • PrintWriter swallows exceptions - I wouldn't use it if I were you
  • FileWriter always uses the platform default encoding - I wouldn't use that, either. I'd use an OutputStream wrapped in an OutputStreamWriter created with a specific encoding.


回答2:

Do not use FileWriter. It is not possible to define character encoding with FileWriter aand you will end up using system default encoding, which usually will not be what you want to use.

Instead use FileOutputStream and an OutputStreamWriter. Yes, it is an extra line of code, but that extra line is required if you want to write robust and bug free code.

OutputStream out = new FileOutputStream("output.txt", true);
Writer writer = new OutputStreamWriter(out, "UTF-8");

Using system default character encoding is the most common source for bugs. Make a habit of learning to not rely on system default character encoding (or system default time zone).