Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to Save a String to a File

  • Last Updated : 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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

  1. Using writeString() method of Files class
  2. Using write() method of Files class
  3. Using writer() method of Filewriter class
  4. Using write() method of Bufferedwriter class
  5. 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:

  1. Create an instance of the file.
  2. Convert the string into a byte array by using string.getBytes() method.
  3. 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:

  1. Create an instance of the file.
  2. Declare the stream with filewriter.
  3. 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:

  1. Create an instance of the file.
  2. Create a stream of PrintWriter and pass the file instance into it.
  3. Call the write method with data.
  4. Flush the stream.
  5. 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 clas
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!!!!



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!