Wednesday, August 25, 2021

4 Ways to Write String to File in Java

There are many ways to write String to File in Java and we will see four ways in this article. Simplest way to write text data into a File is by using FileWriter, it takes care of character encoding and provides simple methods to write String directly into file. Another way to write String is by using PrintWriter object. It provides convinient and much used to print() and println() method to write String to file in Java. Ofcourse you can alawys use FileOutputStream if you are getting String as bytes but its not as efficent as FileWriter. For those, who hates to deal with Java IO mainly to avoid closing files, stream and freeing up resource can use third party library like Apache Commons IO which provides very convinient methods to write String to file without worring about resource cleanup part. 


using FileWriter

using PrintWriter

using FileOutputStream

Apache Commons FileUtils


How to write string to text file in Java using FileOutputStream

how to write string to a file in Java using FileWriter

How to write String to File using PrintWriter in Java

Java 7 one liner to write String to file


Writing text into File using Apache Commons IO

FileUtils class from Apache Commons IO contains some convinient utility methods to write String to text file. 


main advantage of using a PrintWriter for writing String to file is that you can use its convinient print() and println() method to write lines. If you use println() then a line fee will always be inserted on contnet, effecitly writing content in new line. Don't forget to close stream, reader or file once you are done writing on it. This is one area where many developers make mistake, also you must know how to close stream in right way to avoid any issue. If you feel this is too much then you better stick with Apache Commons IO FileUtils class which will take care of closign file properly after writing.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.