0

I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!

informatik01
  • 16,038
  • 10
  • 74
  • 104

2 Answers2

1

I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.

Community
  • 1
  • 1
John Kane
  • 4,383
  • 1
  • 24
  • 42
  • warning off topic: congrats on 3k rep :) – Cruncher Nov 04 '13 at 19:56
  • Not sure its really off topic, the question was about appending to a file, which is what I responded to. I normally write much more detailed responses, but there was no code in the question and I was guessing the person asking the question just didnt know where to really start. (Im also hesitant to give away a lot of code for homework where the person hasnt really shown any of their own work) – John Kane Nov 04 '13 at 20:00
  • 1
    Oh sorry, you misunderstood. I meant that my comment was off topic. – Cruncher Nov 04 '13 at 20:07
  • nice, yeah sorry thanks. – John Kane Nov 04 '13 at 20:10
  • The code I have so far is : Sting fileName ="resources/Scores.txt"; try { PrintWriter fileWriter = new PrintWriter(new FileWriter(fileName,true)); – Diego Dietdricks Nov 04 '13 at 20:11
  • Does this work when you have an empty textfile as well? – Diego Dietdricks Nov 04 '13 at 20:21
  • I think so, but its been a long time. try it out and see if it works. – John Kane Nov 04 '13 at 21:19
0

I haven't tested this, but this should work:

private boolean appendToFile(String fileName, String data, String lineSeparator) 
        throws IOException {
    FileWriter writer = null;
    File file = new File(fileName)

    if (!file.exists()) {
        file.createNewFile();
    }

    try {
        writer = new FileWriter(fileName, true);
        writer.append(data);
        writer.append(lineSeparator);
    } catch (IOException ioe) {
        return false;
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    return true;
}
aa8y
  • 3,854
  • 4
  • 37
  • 62