Java Program to Save a String to a File - GeeksforGeeks

25 Oct, 2021
A demo file on the desktop named ‘gfg.txt’ is used for reference as a local directory on the machine. Creating an empty file before writing a program and give that specific path of that file to the program.
Methods:
Using writeString() method of Files classUsing write() method of Files classUsing writer() method of Filewriter classUsing write() method of Bufferedwriter classUsing write() method of PrintWriter class
Using writeString() method of Files class
Using write() method of Files class
Using writer() method of Filewriter class
Using write() method of Bufferedwriter class
Using write() method of PrintWriter class
Let us discuss every method individually by implementing the same via clean java programs to get a fair idea of working on them.
Method 1: Using writeString() method of Files class
The writeString() method of File Class in Java is used to write contents to the specified file. ‘java.nio.file.Files’ class is having a predefined writeString() method which is used to write all content to a file, using the UTF-8 charset.
Syntax:
Files.writeString(path, string, options)
Parameters: 
Path: File path with data type as Path
String: A specified string that will enter in the file with a return type string.
Options: Different options to enter the string in the file. Like append the string to the file, overwrite everything in the file with the current string, etc
Return Value: This method does not return any value.
Procedure:
Create an instance of the file.
Call the Files.writeString() method with an instance, string and characters set.
Example 
Java
// Java Program to Save a String to a File// Using Files.writeString() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Main classpublic class GFG {       // Main driver method    public static void main(String[] args)    {        // Creating an instance of file        Path path            = Paths.get("C:\\Users\\HP\\Desktop\\gfg.txt");         // Custom string as an input        String str            = "Geeks for Geeks \nWelcome to computer science portal \nHello Geek";         // Try block to check for exceptions        try {            // Now calling Files.writeString() method            // with path , content & standard charsets            Files.writeString(path, str,                              StandardCharsets.UTF_8);        }         // Catch block to handle the exception        catch (IOException ex) {            // Print messqage exception occurred as            // invalid. directory local path is passed            System.out.print("Invalid Path");        }    }}
Output: 
Geeks for Geeks
Welcome to computer science portal
Hello Geek
Method 2: Using write() method of Files class 
java.nio.file.Files class is having a predefined write() method which is used to write a specified text to the file.
Procedure:
Create an instance of the file.Convert the string into a byte array by using string.getBytes() method.Lastly call method namely Files.write() with file instance and the byte array.
Create an instance of the file.
Convert the string into a byte array by using string.getBytes() method.
Lastly call method namely Files.write() with file instance and the byte array.
Example
Java
// Java Program to Save a String to a File// Using Files.write() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Main classpublic class GFG {    // Main driver method    public static void main(String[] args)    {        // Creating an instance of file        Path path            = Paths.get("C:\\Users\\HP\\Desktop\\gfg.txt");         // Custom string as an input        String str            = "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!";         // Converting string to byte array        // using getBytes() method        byte[] arr = str.getBytes();         // Try block to check for exceptions        try {            // Now calling Files.write() method using path            // and byte array            Files.write(path, arr);        }         // Catch block to handle the exceptions        catch (IOException ex) {            // Print message as exception occurred when            // invalid path of local machine is passed            System.out.print("Invalid Path");        }    }}
Output:
Geeks for Geeks
Welcome to computer science portal
Hello Geek!
Method 3: Using writer() method of FileWriter class
Filewriter class is used to write some data on file. This is a simple way of writing the data on file.
Procedure:
Create an instance of the file.
Passing the file instance into filewriter.
Now call writer() method over a filewriter with string data.
Flush the file resource.
Close the file resource.
Example 
Java
// Java Program to Save a String to a File// Using FileWriter class // Importing required classesimport java.io.*;import java.io.File;import java.io.FileWriter;import java.io.IOException; public class GFG{    public static void main(String[] args) throws IOException    {        //creating the instance of file        File path = new File("C:\\Users\\HP\\Desktop\\gfg.txt");             //passing file instance in filewriter        FileWriter wr = new FileWriter(path);         //calling writer.write() method with the string        wr.write("Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!");                 //flushing the writer        wr.flush();                 //closing the writer        wr.close();    }}
Output:
Geeks for Geeks
Welcome to computer science portal
Hello Geek!!
Method 4: Using write() method of BufferedWriter class 
BufferedWriter class basically provides a buffer for writing instance. We can wrap some other writers like PrintWriter and FileWriter into BufferedWriter. BufferedWriter is very efficient for doing multiple write operations on file & writing multiple files. BufferedWriter is very efficient than Filewriter.
Procedure:
Create an instance of the file.Declare the stream with filewriter.Call write() method on stream with string data.
Create an instance of the file.
Declare the stream with filewriter.
Call write() method on stream with string data.
Example
Java
// Java Program to Save a String to a File// Using Files.write() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Main classpublic class GFG {    // Main driver method    public static void main(String[] args)    {        // Creating an instance of file        Path path            = Paths.get("C:\\Users\\HP\\Desktop\\gfg.txt");         // Custom string as an input        String str            = "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!";         // Converting string to byte array        // using getBytes() method        byte[] arr = str.getBytes();         // Try block to check for exceptions        try {            // Now calling Files.write() method using path            // and byte array            Files.write(path, arr);        }         // Catch block to handle the exceptions        catch (IOException ex) {            // Print message as exception occurred when            // invalid path of local machine is passed            System.out.print("Invalid Path");        }    }}
Output:
Geeks for Geeks
Welcome to computer science portal
Hello Geek!!!
Method 5: Using write() method of PrintWriter class
PrintWriter class is an extension of writer class. PrintWriter class is used to write the string data on file using the write() method.
Procedure:
Create an instance of the file.Create a stream of PrintWriter and pass the file instance into it.Call the write method with data.Flush the stream.Close the stream.
Create an instance of the file.
Create a stream of PrintWriter and pass the file instance into it.
Call the write method with data.
Flush the stream.
Close the stream.
Example
Java
// Java Program to Save a String to a File// Using PrintWriter class // Importing required classesimport java.io.*;import java.io.File;import java.io.FileNotFoundException;import java.io.PrintWriter; // Main claspublic class GFG {       // Main driver method    public static void main(String[] args)        throws FileNotFoundException    {        // Creating an instance of file        File path            = new File("C:\\Users\\HP\\Desktop\\gfg.txt");         // Declaring the print writer with path        PrintWriter pw = new PrintWriter(path);         // Now calling writer() method with string        pw.write(            "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!!!");         // Flushing the print writer        pw.flush();         // Lastly closing the printwriter        // using the close() method        pw.close();    }}
Output:
Geeks for Geeks
Welcome to computer science portal
Hello Geek!!!!
surinderdawra388
saurabh1990aror
Java-Files
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character