Java Program to Save a String to a File


Strings, the series of characters, used in Java programming enable to save memory consumption and boost the performance.

We can save a string to a file using Java Program can be initiated in multiple ways and has been introduced in Java version 11. Four parameters can be used to save a string to a file using Java. They are the file path, character sequence, charset, and options.

File path and character sequence; these two are the most important and mandatory for this approach to write into a file. This technique encodes the characters as the content, and it returns the file path, and throws four different types of exceptions. It is always more acceptable to utilize it for the short content of a file.

How one can Save a String to a File?

The File class includes a utility technique to save a string to a file using Java. It can be implemented by FileswriteString(path, string, options). This method comes with two different process. The most basic formation needs a Path of the file to write the data and the textual contents.

Before writing a code it is mandatory to generate an empty file to furnish a specific flow for the program.

To write character oriented data and class to a file, it is convenient to use FileWriter class in Java for file handling. It is important when the writing to the file finished, close it with the close().

There are many methodologies to write a String to File using Java. Here, we will learn and analyze some ways to a file using some examples.

Algorithm to save a String to a File

Here is the general algorithm to save a string to a file in Java −

  • Step 1 − A file including the path of a text file.

  • Step 2  File Output Stream with the object of the file.

  • Step 3 − Stream: Buffered O/P using File Output.

  • Step 4 − Data string conversion to byte array after that.

  • Step 5 − With Buffered Output Stream.write() Encode the byte array to file.

  • Step 6 − Buffered Output Stream and File Output Stream create to release any system resources associated streams.

  • Step 7 − File contents read to string.

  • Step 8 − END

Syntax

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteStringToFile {
 
   public static void main(String[] args) {
      File file = new File("files/123.txt");
      String data = "Hello World!\nWelcome to TP";
      try(FileOutputStream fos = new FileOutputStream(file);
      BufferedOutputStream bos = new BufferedOutputStream(fos)) {
         byte[] bytes = data.getBytes();
         bos.write(bytes);
         bos.close();
         fos.close();
         System.out.print("Data written to file successfully.");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Let us discuss some approaches to save a string to a file −

  • Approach 1 − Implementation of writeString() method

  • Approach 2 − Implementation of write() method of the File class

  • Approach 3 − Implementation of writer() method of the Filewriter class

Implementation of writeString() Method

writeString() is a File Class method of Java to encode a string to a particular file.

Syntax

Files.writeString(path, string, options)

Parameters: writeString() Method

By using the writeString() method, here we will build a Java code by using the below process −

  • The path of a particular file defined with data type.

  • Encode a particular string with return type.

  • The string may have different options in that particular file.

  • Last but not the least, there is no return value for this method.

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TP {
   public static void main(String[] args){
      Path path
      = Paths.get("C:\Users\HP\Desktop\123.txt");
      String str
      = "TP \nWelcome to the portal \nHello Student!";
      byte[] arr = str.getBytes();
      try {
         Files.write(path, arr);
      }
      catch (IOException ex) {    
         System.out.print("Invalid Path");
      }
   }
}

Output

TP
Welcome to the portal
Hello student

Implementation of write() Method of the File Class

java.nio.file.Files, is a method of predefined write() string into a file.

Syntax

public void write(String string)

Parameters: write() Method

Here we have mentioned those two particular parameters for write() method −

  • There is a mandatory parameter of a string, to write.

  • There is no return value for this method.

Example

import java.io;  
public class Write {  
   public static void main(String[] args) {  
      try {  
         Write w = new FileWrite("TP.txt");  
         String content = "I love India";  
         w.write(content);  
         w.close();  
         System.out.println("Executed");  
      } catch IOException e {  
         e.printStackTrace();  
      }  
   }  
} 

Output

Executed
I love India

Implementation of writer() Method of the Filewriter Class

The simplest way to write data on a file using Java is Filewriter class.

Syntax

public class File Writer extends Output Stream Writer  

Parameters: writer() Method

Here we have mentioned those two particular parameters for writer() method −

  • File customization can be done by creating a file writer.

  • Use of "new FileWriter(File fileObj)" to define an object.

Example

package tutorialspoint;  
import java.io.filewriter;  
public class FileWriter {  
   public static void main(String args[]){    
      try{    
         FileWriter fw = new FileWriter("D:\123.txt");    
         fw.write("Welcome to tutorialspoint.");    
         fw.close();    
      }catch(Exception e){System.out.println(e);}    
      System.out.println("Success");    
   }    
}  

Output

Success
Welcome to tutorialspoint

Conclusion

"File handling" is a critical element of any application in Java. There are many methods for creating, reading, updating, and deleting files in Java 11.

  • FileNotFoundException - is an exception when searched file dosen't exist

  • If the file doesn't exist, the new file will be created with no exception

  • Before release the whole process use close(), which calls flush()

In this article, we understood how to compose a code to save a string to a file using Java with some external Java packages.

Updated on: 31-Mar-2023

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements