title: Create a text file if it doesn't exist and append to it if it does using Java BufferedWriter
body: <p>This is probably ridiculously simple for gun Java programmers, yet the fact that I (a relative newbie to Java) couldn't find a simple, straightforward example of how to do it means that I'm going to use the <a href="https://stackoverflow.com/help/self-answer">self-answer</a> option to hopefully prevent others going through similar frustration.</p>
  
  <p>I needed to output error information to a simple text file. These actions would be infrequent and small (and sometimes not needed at all) so there is no point keeping a stream open for the file; the file is opened, written to and closed in the one action.</p>
  
  <p>Unlike other "append" questions that I've come across, this one requires that the file be created on the first call to the method in that run of the Java application. The file will not exist before that.</p>
  
  <p>The original code was:</p>
  
  <pre><code>            Path pathOfLog = Paths.get(gsOutputPathUsed + gsOutputFileName);
              Charset charSetOfLog = Charset.forName("US-ASCII");
              bwOfLog = Files.newBufferedWriter(pathOfLog, charSetOfLog);
              bwOfLog.append(stringToWrite, 0, stringToWrite.length());
              iReturn = stringToWrite.length();
              bwOfLog.newLine();
              bwOfLog.close();
  </code></pre>
  
  <p>The variables starting with gs are pre-populated string variables showing the output location, and stringToWrite is an argument which is passed in.</p>
  
  <p>So the .append method should be enough to show that I wanted to append content, right? </p>
  
  <p>But it isn't; each time the procedure was called the file was left containing only the string of the most recent call.</p>