try {
// write string to a file
Files.write(Paths.get("output.txt"), "Hey, there!".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
To specify a different character encoding other than the default UTF-8, you can do the following:
try {
// create a string list
List<String> contents = Collections.singletonList("Hey, there!");
// write string to a file
Files.write(Paths.get("output.txt"), contents,
StandardCharsets.UTF_16);
} catch (IOException ex) {
ex.printStackTrace();
}
To create a non-existing file or append the string to an existing one, use the following code snippet:
try {
// create a string list
List<String> contents = Collections.singletonList("Hey, there!");
// write string to a file
Files.write(Paths.get("output.txt"), contents,
StandardCharsets.UTF_16,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
} catch (IOException ex) {
ex.printStackTrace();
}