title: Java - open existing file or create one if doesn't exist using IO streams
body: <p>I was following instructions from a Java website (<a href="http://java.sun.com/docs/books/tutorial/essential/io/file.html#createStream" rel="nofollow noreferrer">http://java.sun.com/docs/books/tutorial/essential/io/file.html#createStream</a>) on creating or writing a file using an IO stream. However, the code it provides seems to be broken in multiple places:</p>
  
  <pre><code>import static java.nio.file.StandardOpenOption.*;
  
  Path logfile = ...;
  
  //Convert the string to a byte array.
  String s = ...;
  byte data[] = s.getBytes();
  
  OutputStream out = null;
  try {
      out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
      ...
      out.write(data, 0, data.length);
  } catch (IOException x) {
      System.err.println(x);
  } finally {
      if (out != null) {
          out.flush();
          out.close();
      }
  }
  </code></pre>
  
  <p>For example, Eclipse crashes on the import, and on using the Path class, for starters. However, this tutorial seemed to provide exactly what I want to do - I want to write to a file if it exists (overwrite) or create a file if it doesn't exist, and ultimately I will be writing with an output stream (which gets created here using the .newOutputStream() method). So creating/writing with an output stream seemed like a likely candidate. Does anyone know how to either fix the above so that it works, or a better way to do what I want to do? </p>