In this article, we will explore different ways to write the content to a file in Java. There are several different methods you can use to do it. We will give some advice about which method is the best for writing different data types. It can be helpful for you to choose the best method that will suit your needs.
BufferedWriter is used to write the string content into a file in Java. This writer was specially designed to write text to a character-output stream. It supports buffering characters to improve writing efficiency.
3. Write with FileOutputStream
FileOutputStream was designed to write binary data into a file. In the following example, we get bytes from a simple String and writes them to file using FileOutputStream for the sake of simplicity.
4. Write with PrintWriter
PrintWriter writes formatted representations of objects to a text-output stream. This writer proivdes all methods available in PrintStream, so you can print to a file all kind of Java objects and primitive types.
5. Write with FileWriter
FileWriter is meant for writing streams of characters into a file. In the following example we write simple String FrontBackend.com to a file located in /tmp/test3.txt.
6. Write with DataOutputStream
DataOutputStream can be used to write bytes, primitive types, characters and Strings into a file. It has implemented writeUTF method that writes a string to the underlying output stream using modified UTF-8 encoding.
7. Write with FileChannel
FileChannel is a universal object used for reading, writing, mapping, locking and manipulating a file. File channels are safe for use by multiple concurrent threads.
8. Write with Files
JDK 7 introduce Files utility class. This class comes with static methods that operate on files, directories, or other types of files. Using Files object you can write a string to a file in a single line of code.
9. Conclusion
This article lists several methods used to write content into a file in Java. Different Java writers are meant for different data types. For printing formatted text into a file use PrintWriter class, FileChannel is great for large files, FileOutputStream can write any binary data and DataOutputStream can write also primitive data types like int, long or double.
Code snippets used in this article are available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}