views:

2009

answers:

1

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?

+2  A: 

That example seems to be using APIs that are not part of Sun Java 6.

Class Path and the package java.nio.file are part of an API that is going to be added in Sun JDK 7. Note that the link to the documentation of Path points to the API documentation of OpenJDK, Sun's open source development version of Java.

So, you cannot use those APIs if you are using regular Sun Java 6.

Read the warning on the start page of the tutorial:

File I/O (Featuring NIO.2)

This section is being updated to reflect features and conventions of the upcoming release, JDK7. You can download the current JDK7 Snapshot from java.net. We've published this preliminary version so you can get the most current information now, and so you can tell us about errors, omissions, or improvements we can make to this tutorial.

In Sun Java 6 you can just use FileOutputStream. It will automatically create a new file if the file doesn't exist or overwrite an existing file if it exists:

FileOutputStream out = new FileOutputStream("filename.xyz");
out.write(data, 0, data.length);

Note: For writing text files (what is what you seem to want to do), use a Writer (for example FileWriter) instead of using an OutputStream directly. The Writer will take care of converting the text using a character encoding.

See the Java SE 6 API Documentation (especially the docs of the packages java.io) for information about what's available in Java SE 6.

Jesper
can you suggest another way for me to do what I want to do without these API?
hatorade
JDK 6 is the development kit for Sun Java 6. JDK 7 is going to be the next release of Sun Java, to be released in March 2010.
Jesper