Problem with trying to write to a text file.

Discussion in 'Plugin Development' started by h4344, Nov 26, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    h4344

    When i use this code it writes the information like it should but dosent save that information in a way. So for example when i join the server it writes my name and time in the text document correctly but when i rejoin it just replaces it with the new time "im sure it replaces the whole text but my name stays the same". I tried adding a " "/n" " inside where it says what should be printed on the end to try to add a new line but it still seems to just write on the first line.

    public class MyPlayerListener extends PlayerListener {
    @Override
    public void onPlayerJoin(PlayerJoinEvent event) {
    Player player = event.getPlayer();
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter("Logged Players.txt"));
    String strDateFormat = "HH:mm:ss a";
    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
    Date date = new Date();
    out.write(player.getName() + " " + sdf.format(date) + "\n");
    out.close();
    }
    catch (IOException e) {
    }
    }
    }
     
  2. Offline

    ImperatorFeles

    What's happening is that every time you write to the file, you overwrite it with a new file. What you need to do is:

    Code:
    BufferedWriter out = new BufferedWriter(new FileWriter("Logged Players.txt", true));
    Note the second argument to the FileWriter constructor, "true". This is an optional append flag which when set to true will append to a file instead of overwriting it. Adding that argument should fix your problem.
     
  3. Offline

    Pazflor

    You should put a newLine in there too, or else the file will be very messed up..
    Like this:
    Code:java
    1.  
    2. out.write(player.getName() + " " + sdf.format(date) + "\n");
    3. out.newLine();
    4. out.close();
    5.  
     
Thread Status:
Not open for further replies.

Share This Page