我按照 Java 网站 ( http://java.sun.com/docs/books/tutorial/essential/io/file.html#createStream ) 的说明使用 IO 流创建或写入文件。但是,它提供的代码似乎在多个地方被破坏:
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();
}
}
例如,对于初学者来说,Eclipse 在导入和使用 Path 类时会崩溃。但是,本教程似乎提供了我想要做的事情 - 如果文件存在(覆盖),我想写入文件,如果文件不存在,我想创建一个文件,最终我将使用输出流(其中使用 .newOutputStream() 方法在此处创建)。因此,使用输出流创建/写入似乎是一个可能的候选者。有谁知道如何解决上述问题以使其正常工作,或者是一种更好的方法来做我想做的事情?