In Java, there are a number of classes for File handling and Input/Output operations. No matter, whether you want to write into a file line by line, character by character or byte by byte, you can do it in minutes. In this tutorial, we will see 7 different ways of How do you write to a File in Java? So, Let’s get started –
Some Prior Knowledge – Write to File : Java
Before jumping on to the solutions and programmatic implementation of How do you write to a file in Java, you must have some basic knowledge or at least heard about these major concepts –
- Loops in Java,
- String manipulation like- Traversing each character or String split(),
- Exception handling (try-catch-throw) mechanism.
As, In this tutorial, you will see that many of the solutions of writing text to File in Java, is using these concepts. So, In case, if you have not heard about any of them, then first read and understand those Core Java Concepts, and then continue with this post to better understand – How do you write to a File in Java?
Simple Solutions
(1) Write to File – Java BufferedOutputStream Class
The BufferedOutputStream class in Java, is used for buffering an output stream. That basically means the data or text is buffered (or stored) in memory and not written to the output stream on each write() method call. You should flush() the buffer at a suitable time interval and close the stream using the close() method to force the final buffer out.
Here are some other important points to remember –
- You can use BufferedOutputStream class by importing it from java.io package.
- It contains 2 protected member variables : buf and count.
- The field buf is used to store the data.
- The field count is used to count the number of valid bytes in the buffer.
Solution :
package com.shubhamklogic.java.file.io; // Simple Java program to write into a File using : BufferedOutputStream import java.io.*; class SolutionBufferedOutputStream // Explaining Step-by-Step { public static void main(String args[]) { try { // Setting the path for File String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; // Logging : What's going in background System.out.println("[INFO] 1: BufferedOutputStream Object Created"); FileOutputStream file = new FileOutputStream(path + "WrittenSuccessfully.txt"); BufferedOutputStream bout = new BufferedOutputStream(file); char charArr[] = yourMessege.toCharArray(); for (char ch: charArr) bout.write((int) ch); System.out.println("[INFO] 2: Written in File - Successfully"); bout.flush(); System.out.println("[INFO] 3: Buffer cleaned"); bout.close(); System.out.println("[INFO] 4: Buffer closed"); file.close(); System.out.println("[INFO] 5: File closed"); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into a text File : WrittenSuccessfully.txt
[INFO] 1: BufferedOutputStream Object Created [INFO] 2: Written in File - Successfully [INFO] 3: Buffer cleaned [INFO] 4: Buffer closed [INFO] 5: File closed
Note*** :
To read and write to file in Java, first you need to set the path for the File. All programs in this tutorial are developed in a Windows machine, as you can see the path variable contains directories separated by double back-slashes \\.
Don’t worry, If you are working with macOS, Ubuntu, or any other Operating System, just use System.getProperty(“user.home”) to get the home directory for your Computer system.
Here are some other valuable System properties for file Handling in Java :
- “file.separator” : To get the Character that separates components of a file path. This is “/” on UNIX and “\” on Windows.
- “java.class.path” : To get the Path used to find directories and JAR archives containing class files. Elements of the classpath are separated by a platform-specific character specified in the path.separator property.
- “java.home” : To get the Installation directory for Java Runtime Environment (JRE)
- “java.vendor” : To get the JRE vendor name
- “java.vendor.url” : To get the JRE vendor URL
- “java.version” : To get the JRE version number
- “line.separator” : To get the Sequence used by operating system to separate lines in text files
- “os.arch” : To get the Operating system architecture
- “os.name” : To get the Operating system name
- “os.version” : To get the Operating system version
- “path.separator” : To get the Path separator character used in java.class.path
- “user.dir” : To get the User working directory
- “user.home” : To get the User home directory
- “user.name” : To get the User account name
(2) Write to File – Java FileOutputStream class
A few useful points about the FileOutputStream class in Java is,
- It’s basically an output stream for writing text or any type of data to a File or FileDescriptor.
- The FileOutputStream class is used for writing bytes streams such as image data.
- You can use it with bytes of some data that can’t be represented as native text/string such as a PDF file, excel documents, image files etc.
Here is how do you write to a File in Java using FileOutputStream –
// Java program to write into a File using FileOutputStream class package com.shubhamklogic.java.file.io; import java.io.*; class SolutionFileOutputStream // Explaining Step-by-Step { public static void main(String args[]) { try { // Setting the path for file String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; // Creating Object of class FileOutputStream FileOutputStream fileWriter = new FileOutputStream(path + "WrittenSuccessfully.txt"); System.out.println("[INFO] 1: FileOutputStream object Created ..."); // Writing to file for (char ch: yourMessege.toCharArray()) fileWriter.write(ch); System.out.println("[INFO] 2: File Written Successfully..."); // Writing Done, Now close the file object... fileWriter.close(); System.out.println("[INFO] 3: File Closed..."); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into a text File : WrittenSuccessfully.txt
[INFO] 1: FileOutputStream object Created ... [INFO] 2: File Written Successfully... [INFO] 3: File Closed ...
(3) Write to File – Java ByteArrayOutputStream class
The ByteArrayOutputStream Java class is best used for writing some common data into multiple files.
- It writes the data in the form of bytes, or more specifically, into a byte array.
- And It can be written to multiple streams later.
- The ByteArrayOutputStream process the information as a Shareable – Container, technically speaking a Buffer. Because, it always holds a copy of data and forwards it to multiple streams.
- As the amount of data increases, The buffer of ByteArrayOutputStream automatically grows as well.
Here is how do you write to a File in Java using ByteArrayOutputStream object –
// Java program to write into a File using ByteArrayOutputStream class package com.shubhamklogic.java.file.io; import java.io.*; class SolutionByteArrayOutputStream // Explaining Step-by-Step { public static void main(String args[]) { try { // Setting the path for file String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; System.out.println("[INFO] 1: Path and yourMessege is set ..."); // Creating Objects of FileOutputStream and ByteArrayOutputStream FileOutputStream fileWriter1 = new FileOutputStream(path + "WrittenSuccessfully1.txt"); FileOutputStream fileWriter2 = new FileOutputStream(path + "WrittenSuccessfully2.txt"); ByteArrayOutputStream bufferWriter = new ByteArrayOutputStream(); System.out.println("[INFO] 2: ByteArrayOutputStream object created ..."); // Writing to Buffer memory for (char ch: yourMessege.toCharArray()) bufferWriter.write((int) ch); System.out.println("[INFO] 3: Writing to Buffer memory ..."); // Writing from Buffer to Files bufferWriter.writeTo(fileWriter1); bufferWriter.writeTo(fileWriter2); System.out.println("[INFO] 4: Flushing Buffer and Closing Files ..."); bufferWriter.flush(); bufferWriter.close(); System.out.println("[INFO] 5: Successfully written in both files ..."); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into 2 text Files : WrittenSuccessfully1.txt and WrittenSuccessfully2.txt
[INFO] 1: Path and yourMessege is set ... [INFO] 2: ByteArrayOutputStream object created ... [INFO] 3: Writing to Buffer memory ... [INFO] 4: Flushing Buffer and Closing Files ... [INFO] 5: Successfully written in both files ...
(4) Write to File using Java FilterOutputStream class
The FilterOutputStream class extends the OutputStream class. It has same number of methods with same signature as the OutputStream class contains. However, the methods of FilterOutputStream class are feature rich in comparison to its super class.
Here is how do you write to a File in Java using FilterOutputStream –
// Java program to write into a File using FilterOutputStream class package com.shubhamklogic.java.file.io; import java.io.*; class SolutionFilterOutputStream // Explaining Step-by-Step { public static void main(String args[]) { try { // Setting the path for file String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; System.out.println("[INFO] 1: Path and yourMessege is set ..."); // Creating Objects to manage and access file File yourFile = new File(path + "WrittenSuccessfully.txt"); FileOutputStream fileStreamObj = new FileOutputStream(yourFile); FilterOutputStream filter = new FilterOutputStream(fileStreamObj); System.out.println("[INFO] 2: Filter Object Created ..."); byte bytes[] = yourMessege.getBytes(); filter.write(bytes); System.out.println("[INFO] 3: Writing in File : Done ..."); filter.flush(); filter.close(); fileStreamObj.close(); System.out.println("[INFO] 4: Filter closed ..."); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into a text File : WrittenSuccessfully.txt
[INFO] 1: Path and yourMessege is set ... [INFO] 2: Filter Object Created ... [INFO] 3: Writing in File : Done ... [INFO] 4: Filter closed ...
(5) Write to File using Java BufferedWriter class
Some key points about the BufferedWriter class is –
- It’s basically a sub class of java.io.Writer class.
- The BufferedWriter class object writes text to character based output stream.
- It provides efficient writing of single characters, arrays, and strings.
- Technically speaking, the BufferedWriter class works with relatively large group of data at once. This results less the number of write operations and better performance.
Here is how do you write to a File in Java using BufferedWriter object –
// Java program to write into a File using BufferedWriter class package com.shubhamklogic.java.file.io; import java.io.*; class SolutionBufferedWriter // Explaining Step-by-Step { public static void main(String args[]) { try { // Setting the path for file String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; System.out.println("[INFO] 1: Path and yourMessege is set ..."); // Creating Objects to manage and access file FileWriter writer = new FileWriter(path + "WrittenSuccessfully.txt"); BufferedWriter buffer = new BufferedWriter(writer); System.out.println("[INFO] 2: BufferedWriter Object created ..."); // Writing to File buffer.write(yourMessege); System.out.println("[INFO] 3: Text written in file, Successfully ..."); // Close the buffer buffer.close(); System.out.println("[INFO] 4: Buffer closed ..."); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into a text File : WrittenSuccessfully.txt
[INFO] 1: Path and yourMessege is set ... [INFO] 2: BufferedWriter Object created ... [INFO] 3: Text written in file, Successfully ... [INFO] 4: Buffer closed ...
(6) Write to File – Java StringWriter class
Here are some key points to be remembered about this class –
- In Java, the StringWriter class directly works with characters that we provide.
- It collects the output from the string buffer memory area, which can be used to construct a string. The StringWriter class inherits the Writer class.
Here is how do you write to a File in Java using StringWriter object –
// Java program to write into a File using StringWriter class package com.shubhamklogic.java.file.io; import java.io.*; class SolutionStringWriter { // Explaining Step-by-Step public static void main(String args[]) { try { // Setting the path for file String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; System.out.println("[INFO] 1: Path and yourMessege is set ..."); // Creating Objects to manage and access file FileWriter theFileWriter = new FileWriter(path + "WrittenSuccessfully.txt"); StringWriter theStringWriter = new StringWriter(); // Writing to the file theStringWriter.write(yourMessege); theFileWriter.write(theStringWriter.toString()); System.out.println("[INFO] 2: Written to File, Successfully ..."); // Closing writers theFileWriter.close(); theStringWriter.close(); System.out.println("[INFO] 3: File writers are closed ..."); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into a text File using StringWriter : WrittenSuccessfully.txt
[INFO] 1: Path and yourMessege is set ... [INFO] 2: Written to File, Successfully ... [INFO] 3: File writers are closed ...
(7) Write to File – Java FileWriter class
The FileWriter class is another character stream class, that works with characters of some text / String –
- FileWriter class in Java, is basically used to write character-oriented data to a file.
- You can use FileWriter class and object for File handling in Java.
- However, unlike the FileOutputStream class, when you’ll use FileWriter object, you don’t need to convert string into byte array because it provides method to write string directly.
Here is how do you write to a File in Java using FileWriter object –
// Java program to write into a File using FileWriter class package com.shubhamklogic.java.file.io; import java.io.*; class SolutionFileWriter // Explaining Step-by-Step { public static void main(String args[]) { try { // Setting the path for file String path = "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\"; // Setting the messege String yourMessege = "Don't Just Learn, Master core Java - ShubhamKLogic.com"; System.out.println("[INFO] 1: Path and yourMessege is set ..."); // Creating Objects to manage and access file FileWriter theFileWriter = new FileWriter(path + "WrittenSuccessfully.txt"); System.out.println("[INFO] 2: File writer is closed ..."); theFileWriter.write(yourMessege); theFileWriter.close(); System.out.println("[INFO] 3: Writing in File done..."); } catch (Exception e) { System.out.println("[INFO] Hey, You got an Exception - " + e.getMessage()); } } }
Output :
Let’s run the above Java program to write into a text File : WrittenSuccessfully.txt
[INFO] 1: Path and yourMessege is set ... [INFO] 2: File writer is closed ... [INFO] 3: Writing in File done...
Wrap Up
So far, we have learned in Java, write to File line by line as well as by character and bytes. Now, we know How to create File in Java and 7 different ways to develop Java program to write into a text file.
I hope, this article helped you to learn a bit more about Java file handling concepts. If you have any doubt or query, then do comment or send me a direct mail via Google, I’ll try my best to give you the solution within a day.
Also, rate this article on Facebook and, Don’t forget to check Other Useful Java Articles that you may like :
Read Next :
→ Top 4 ways to Generate Random Numbers in Java ( Tutorial )
→ 50+ Popular Java Interview Questions (OOPs, Multi-threading, etc) ( Interview Related )
→ How to use split() in Java? – Explained in Detail ( Tutorial )
→ volatile keyword in Java – How to use volatile in Multithreading? ( Tutorial )
→ Full List of Useful articles & resources ( Core Java Concepts )