Open In App

Java Program to Create String from Contents of a File

A File is a computer resource which is deployed to store different types of data such as text, image, video, to name a few. It is basically a collection of data bound to a single entity. While using your computer, it becomes essential to be able to deal with files and in this article we will be learning about various ways to read data from files. We will be using the File class extensively for the same. After reading the contents of the file, we will be storing them in a string which is typically an array of characters. For more information on String class, click here.

There are 4 methods by which we can read the contents of a file and convert them into a string in Java. The 4 approaches are mentioned below :

  1. Using readString() method of the Files class
  2. Reading the contents of the file in the form of a bytes array and then converting it into a string
  3. Reading the file line by line using the BufferedReader class
  4. Storing the contents of the file in the form of a stream and then making a string from it

Using this approach, we deploy the readString() function.

Algorithm :

  1. Read the path of the file as a string.
  2. Convert the string into a Path variable.
  3. Give this Path variable as a parameter to readString() function.
  4. Return the string to the main function.

Implementation :




// java program to create String
// from the contents of a file
  
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
  
class GFG {
  
    // declaring the method
    public static String fileToString(String p) throws IOException
    {
  
        // converting the string variable
        // to Path variable
        Path path = Paths.get(p);
  
        // directly converting the contents
        // of file to String
        String contents = Files.readString(path);
        return contents;
    }
  
    // driver code
    public static void main(String[] args)
        throws IOException
    {
  
        // printing the contents of the string
        // by calling the fileToString() method
  
        // parameter would be "C:\\Users\\harshit\\"
        // + "Desktop\\text.txt" for Windows User
        System.out.print(fileToString("/home/mayur/GFG.java"));
    }
}



Approach 2 :

Using this approach, we first read the contents of the file and store them as a byte array. Finally, we convert it into a String.

Algorithm :

  1. First, pass the path as a String variable to the function.
  2. Next, convert it into a Path Variable.
  3. Pass this variable as a parameter to readAllBytes() function of the Files class.
  4. Next, convert this array to a String.

Implementation :




// java program to create a String
// from the contents of a File
  
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
  
class GFG {
    public static String fileToString(String p)
    {
  
        // converting string variable
        // to Path variable
        Path path = Paths.get(p);
  
        // initializing an empty byte array
        byte[] b = {};
  
        // try block
        try {
  
            // storing the bytes in the array
            b = Files.readAllBytes(path);
        }
  
        // catch block
        catch (IOException e) {
  
            // printing the error
            e.printStackTrace();
        }
  
        // converting the byte array to String
        String contents = new String(b);
        return contents;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // printing the string returned by the
        // fileToString() method
  
        // path would have been "C:\\Users\\"
        // + "harshit\\Desktop\\text.txt"
        System.out.print(fileToString("/home/mayur/GFG.java"));
    }
}

Approach 3 :

Using this approach, we read the contents of the file one line at a time till we find a null character using readLine() function of the BufferedReader class. 

Algorithm :

  1. Pass the String variable containing the path to the file while calling the fileToString() method
  2. Initialize a FileReader object with the path variable as the parameter.
  3. Read the contents of the file using BufferedReader class.
  4. Stop when you see a null character.
  5. Store the contents in a String while appending the new line character after every line accepted.

Implementation :




// java program to create a String
// from the contents of a file
  
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
  
class GFG {
  
    // declaring the method
    public static String fileToString(String p)
    {
  
        // initializing the variable to
        // store the string
        String contents = "";
  
        // Instantiating the FileReader class
        try (FileReader f = new FileReader(p)) {
  
            // instantiating the BufferedReader class
            BufferedReader br = new BufferedReader(f);
  
            // to store the current line read by the
            // readLine () method
            String current = "";
  
            // looping till we find the null char
            while ((current = br.readLine()) != null)
  
                // storing the contents in string
                contents += current + "\n";
        }
  
        // catch block
        catch (IOException e) {
  
            // printing the error
            e.printStackTrace();
        }
  
        // returning the string
        return contents;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // printing the string
        // parameter would have been "C:\\Users\\"
        // + "harshit\\Desktop\\text.txt"
        // for Windows users
        System.out.print(
            fileToString("/home/mayur/GFG.java"));
    }
}

Approach 4 :

Using this approach, we read the contents of a file and store them in Stream of String. Next, we convert this Stream into a String array and iterate through it. We store all the strings in a single string created by a StringBuffer class.

Algorithm :

  1. Passing the string path to the function fileToString().
  2. Convert this string to a Path variable.
  3. Initialize a StringBuffer object to store the final string.
  4. Read the contents and store them in a Stream of String.
  5. Convert this String Stream into a String array.
  6. Iterate through this array and store all the strings in the StringBuffer object.
  7. Return the final string.

Implementation :




// java program to create a string
// from the contents of a File
  
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.charset.*;
import java.util.stream.*;
  
class GFG {
  
    // declaring the method
    public static String fileToString(String p)
    {
  
        // converting string to path
        // variable
        Path path = Paths.get(p);
  
        // initializing the StringBuffer class
        StringBuffer s = new StringBuffer();
  
        // initializing the final variable
        String contents = "";
  
        // storing the contents in a Stream
        try (Stream<String> str
             = Files.lines(path, StandardCharsets.UTF_8)) {
  
            // converting stream to string array
            String[] arr
                = str.toArray(size -> new String[size]);
  
            // iterating through the String array
            for (String string : arr) {
                contents += string + "\n";
            }
        }
  
        // catch block
        catch (IOException e) {
  
            // printing the error
            e.printStackTrace();
        }
        return contents;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // printing the string
        // parameter would be "C:\\Users\\harshit"
        // + "\\Desktop\\text.txt" for Windows Users
        System.out.print(
            fileToString("/home/mayur/GFG.java"));
    }
}


Article Tags :