For each class/method dedicated to reading a text file (for example, BufferedReader and readString()) Java provides its counterpart for writing a text file (for example, BufferedWriter and writeString()). Here is an example of writing a text file via BufferedWriter:
Path textFile = Paths.get("sample.txt");
try (BufferedWriter bw = Files.newBufferedWriter(
textFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE,
StandardOpenOption.WRITE)) {
bw.write("Lorem ipsum dolor sit amet, ... ");
bw.newLine();
bw.write("sed do eiusmod tempor incididunt ...");
}
A very handy method for writing an Iterable into a text file is Files.write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options). For example, let's write the content of a list into a text file (each element from the list is written on a line in the file):
List<String> linesToWrite = Arrays.asList("abc", "def", "ghi");
Path textFile = Paths.get("sample.txt");
Files.write(textFile, linesToWrite, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
Finally, to write a String to a file, we can rely on the Files.writeString(Path path, CharSequence csq, OpenOption... options) method:
Path textFile = Paths.get("sample.txt");
String lineToWrite = "Lorem ipsum dolor sit amet, ...";
Files.writeString(textFile, lineToWrite, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
Finally, writing a text file via MappedByteBuffer can be accomplished as follows (this can be useful for writing huge text files):
Path textFile = Paths.get("sample.txt");
CharBuffer cb = CharBuffer.wrap("Lorem ipsum dolor sit amet, ...");
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(
textFile, EnumSet.of(StandardOpenOption.CREATE,
StandardOpenOption.READ, StandardOpenOption.WRITE))) {
MappedByteBuffer mbBuffer = fileChannel
.map(FileChannel.MapMode.READ_WRITE, 0, cb.length());
if (mbBuffer != null) {
mbBuffer.put(StandardCharsets.UTF_8.encode(cb));
}
}