I was following instructions from a Java website (http://java.sun.com/docs/books/tutorial/essential/io/file.html#createStream) on creating or writing a file using an IO stream. However, the code it provides seems to be broken in multiple places:
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();
}
}
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?