Java Program to Save a String to a File
Last Updated :
03 Mar, 2023
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 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 classes
import 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 class
public 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.
Example
Java
// Java Program to Save a String to a File
// Using Files.write() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
// Main class
public 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 classes
import 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.
Example
Java
// Java Program to Save a String to a File
// Using Files.write() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
// Main class
public 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.
Example
Java
// Java Program to Save a String to a File
// Using PrintWriter class
// Importing required classes
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
// Main class
public 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!!!!
Similar Reads
Java Program to Read a File to String
There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Given a text file, the task is to read the contents
8 min read
Java Program to Add Characters to a String
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
4 min read
Java Program to Rename a File
Changing the name of the file is known as Renaming the file. Rename operation is possible using renameTo() method belongs to the File class in java. A. renameTo() Method The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.
2 min read
Java Program to Convert Boolean to String
In Java programming, you might come across the need to convert a simple "true" or "false" boolean value into a String. It may seem like a challenging task, but fear not! In this article, You will explore some methods to convert a boolean value to a string in Java Method for Boolean to String Convers
4 min read
Java Program to Write Data to Temporary File
A Temporary file or a Temp file is a file that is created in order to hold information for some time while a file is being created or modified. After the successful execution of the program or after the program is closed, the temporary file is deleted. Other advantages of having a temporary file are
3 min read
Java Program to Convert InputStream to String
Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read
4 min read
Java Program to Create a Temporary File
A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement. Type of Fi
6 min read
Java Program to Convert String to InputStream
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations. Illustration: Input : String : "Geeks for Geeks" Output : Input Stream : Geeks for Geeks Input : String : "A computer science portal" Output : Input stream : A computer science portal In order
2 min read
Java Program to Convert String to Object
In-built Object class is the parent class of all the classes i.e each class is internally a child class of the Object class. So we can directly assign a string to an object. Basically, there are two methods to convert String to Object. Below is the conversion of string to object using both of the me
2 min read
Java String Programs
A String in Java is a sequence of characters that can be used to store and manipulate text data and It is basically an array of characters that are stored in a sequence of memory locations. All the strings in Java are immutable in nature, i.e. once the string is created we can't change it. This arti
4 min read