StandardOpenOption Write Modes CreateNew Append
Control Files.writeString with CREATE_NEW, CREATE, APPEND, and TRUNCATE_EXISTING so overwrites, appends, and fail-on-existing behavior stay explicit.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class WriteOptions {
public static void main(String[] args) throws IOException {
Path target = Files.createTempFile("write-options-", ".txt");
// writeString 默认 CREATE + TRUNCATE_EXISTING:已存在则清空重写
Files.writeString(target, "v1\n");
// CREATE_NEW:只在目标不存在时创建,已存在直接抛异常,绝不覆盖
try {
Files.writeString(target, "overwritten", StandardOpenOption.CREATE_NEW);
} catch (IOException exists) {
System.out.println("CREATE_NEW rejected: " + exists.getClass().getSimpleName());
}
// CREATE + APPEND:不存在则创建,存在则从末尾追加,不截断
Files.writeString(target, "v2\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println(Files.readString(target).strip());
Files.deleteIfExists(target);
}
}What the code does
StandardOpenOption Write Modes CreateNew Append keeps everything in the class WriteOptions.
Applying it
The demo output is labeled (CREATE_NEW rejected:), so every printed line maps back to its originating operation.
Statements that matter
Files.writeString(target, "v2\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Files.writeString(target, "overwritten", StandardOpenOption.CREATE_NEW);
Path target = Files.createTempFile("write-options-", ".txt");
Interactive Tools for This Topic
FAQ
- What does StandardOpenOption Write Modes CreateNew Append print when run?
- Running the file directly is enough — expect labeled output lines such as `CREATE_NEW rejected:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.