In the below examples, we are going to create text file (sample.txt) with below content.
Read text files using java.nio.Files utility class Read text files using using java.io.FileWriter class Read text files using using java.io.BufferedWriter class
java.nio.Files is an utility class, which has lot of static methods that operate of files, in the below example we are going to useFiles.writeString(Path, CharSequence) method which writes text content into the file, first argument to this method is Path where to write file, second argument is the String text that we want to write.
Note: Note that
You can also pass file
Third parameter to
FileWriter class can be used to write text content into a file, and this is meant to be used for writing streams of characters only.
In the above code,
Default behaviour of above code is it always overrides the content. If you want to append text to the file instead,
you can enable
-
BufferedWriter class expects anotherjava.io.Writer type as an input argument to delegate the actual I/O operations to that. - BufferedWriter maintains a character array as a buffer in the memory to store chunks of characters data before writing to the actual file,
it writes to the file once the buffer is filled and any remaining characters will be written when closing the writer at the end.
(
BufferedWriter isAutoClosable , using below syntax of try block, it automatically closes at the end of try block), thus minimizing number of I/O operations. - BufferedWriter comes handy if you want to write data to files or sockets or to any other source and it is thread-safe (synchronized)
Note: Default buffer size is 16KB. You can change buffer size using
Above examples source code can be found at