To create a file and write into it is the most common task in Java. Java provides various ways to create files and write content for them. Whether you’re working with simple text files or more complex binary files, Java has built-in support for file handling by providing multiple methods.
In this blog, we will explore how to create a file, write to it in Java, and explore advanced file-writing techniques in more detail.
Table of Contents:
Java Program to Create a File
Java provides multiple methods to create a new file, let’s explore these methods in more detail:
Method 1. Using File.createNewFile()
The File.createNewFile() method is one of the simplest and most commonly used methods in Java for creating a file. It creates a new file if it does not exist and returns true, otherwise, if the file already exists, it returns false
Example:
Output:
Explanation: In the above code, we are creating a new file named “example.txt”, after creating the file:
- If the file is successfully created, the program prints “File created: example.txt“.
- If the file already exists, it prints “File already exists.” instead of creating a duplicate.
- If an error occurs (e.g., permission issues, invalid file path), the program catches the exception and prints “An error occurred“.
Method 2. Using FileOutputStream.write(byte[] b)
If you want to create a new file and write data into it immediately, you can use the FileOutputStream class along with its write() method. The FileOutputStream class in Java is primarily used for writing byte data to a file. It is commonly utilized when working with binary data, such as images or audio files, but it can also be used for writing text files by converting text into bytes.
Example:
Output:
Explanation: The above code creates a new file named ”intellipaat.txt” using FileOutputStream class,
- If the file does not exist, it is created.
- If the file already exists, it is overwritten.
- If an error occurs (e.g., permission issues, invalid file path), the program catches the exception and prints the error message.
Method 3. Java NIO: Using Files.write()
Java NIO (New Input/Output) provides an efficient and easy-to-use method to write data to a file using the Files.write() method. It creates a new file if it does not exist, or overwrites the file if it already exists.
Example:
Output:
Explanation: Here we have defined a string and used NIO (java.nio.file) to create a file named “Java_Resources.txt” and write the data into it.
Java Program to Write into a File
Java provides multiple methods to write content into a file, let’s explore all of these methods in more detail:
Method 1: Using writeString() Method
The writeString() method is a modern way to write text to a file in Java. It was introduced in Java 11 as part of the java.nio.file.Files class.
Example:
Output:
Explanation: In the above code, we have created a file named “example.txt” and written content (Hello intellipaat) into it using writeString() method.
Method 2: Using FileWriter Class
The FileWriter class in Java is a part of the java.io package and is commonly used for writing character data to a file. this method is used for adding small content to the file. It automatically creates a new file, if it does not exist.
Example:
Output:
Explanation: In the above code, we have written content to the file example.txt using the FileWriter class and displayed a message after successfully writing the content.
Method 3: Using BufferedWriter Class
The BufferedWriter class in Java is used to write text to a character-output stream while buffering the characters to provide efficient writing of single characters, arrays, and strings. This method is used when we have to write large text files, and writing line by line data to a file. This method is faster than FileWriter() method due to internal buffering.
Example:
Output:
Explanation: In the above code, we have written content to the file using BufferedWriter() Class and displayed a message after successfully writing the content.
Method 4: Using FileOutputStream Class
The FileOutputStream class is used for writing binary data to files, but it can also be used for text data by converting strings to bytes.
Example:
Output:
Explanation: The FileOutputStream class is used to write content into a file. If an error occurs, it will be caught using the catch block.
Method 5: Using FileChannel Class
The FileChannel class in Java is part of the NIO (New Input/Output) package and is used for writing data to a file with higher performance and better flexibility compared to traditional I/O streams. It works with buffers and is suitable for large files and non-blocking I/O operations.
Example:
Output:
Explanation: In the above code, we have created a new file named “example.txt”, and written content(Learning Java NIO with Intellipaat!) into it.
Method 6: Using DataOutputStream Class
The DataOutputStream class in Java is used to write primitive data types (e.g., int, float, double, boolean, char, etc.) as binary data to an output stream.
Example:
Output:
Explanation: In the above code, we have written content of different data types like: Integer, double, String, and Boolean, and written data to the file using dos.writeInt(), dos.writeDouble(), dos.writeBoolean(), and dos.writeUTF().
Advanced File Writing Methods
Here are some advanced methods by which you can write text into your file:
Method 1: Using RandomAccessFile for Non-Sequential Access
The RandomAccessFile allows you to read and write data at any position in the file. We can write or update data at any time. You can move the file pointer using seek().
Example:
Output:
Explanation:
- In the above code, we have opened (or created) a file named randomAccess.txt in read-write (rw) mode.
- We have written a string (“Hello, Intellipaat!”) and an integer (100) to the file.
- Reads the data from the beginning and prints it.
- Overwrites the string at the beginning of the file with “Java Learner!” (the integer remains unchanged).
- Reads and prints the updated string to show the modification.
Method 2: Using ObjectOutputStream for Writing Objects
If you need to write objects (including custom objects) to a file, ObjectOutputStream helps you to achieve this task.
Example:
Output:
Explanation: The above code creates a Student object to a file (student.dat) using ObjectOutputStream (serialization) and reads the content of the file using ObjectInputStream (deserialization).
Conclusion
So far in this article, we have explored different methods to create a file and write data into the file in Java. We have explored from basic file creation with File.createNewFile() to more advanced methods like RandomAccessFile and ObjectOutputStream. By exploring all the methods to write content into the file, you can choose the best approach for your application.
To become a Java Expert, you may refer to our Java Programming course.
FAQs
1. How to write String to file in Java?
To write string to file in Java, we have to use some built-in classes like FileWriter, BufferedWriter, or Files.writeString().
2. How to store text in Java?
To store text in a file, you can use FileWriter or Files.write() methods.
3. How to write into an existing file in Java?
To write into an existing file, we have to use FileWriter(“fileName”, true) with true as the second parameter.
4. How to write to a file in Java without overwriting?
We have to open FileWriter in append mode like the new FileWriter(“file.txt”, true) to avoid overwriting.