Java Program to Create String from Contents of a File
Last Updated :
17 Nov, 2020
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 :
- Using readString() method of the Files class
- Reading the contents of the file in the form of a bytes array and then converting it into a string
- Reading the file line by line using the BufferedReader class
- 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 :
- Read the path of the file as a string.
- Convert the string into a Path variable.
- Give this Path variable as a parameter to readString() function.
- Return the string to the main function.
Implementation :
Java
// 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 :
- First, pass the path as a String variable to the function.
- Next, convert it into a Path Variable.
- Pass this variable as a parameter to readAllBytes() function of the Files class.
- Next, convert this array to a String.
Implementation :
Java
// 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 :
- Pass the String variable containing the path to the file while calling the fileToString() method
- Initialize a FileReader object with the path variable as the parameter.
- Read the contents of the file using BufferedReader class.
- Stop when you see a null character.
- Store the contents in a String while appending the new line character after every line accepted.
Implementation :
Java
// 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 :
- Passing the string path to the function fileToString().
- Convert this string to a Path variable.
- Initialize a StringBuffer object to store the final string.
- Read the contents and store them in a Stream of String.
- Convert this String Stream into a String array.
- Iterate through this array and store all the strings in the StringBuffer object.
- Return the final string.
Implementation :
Java
// 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"));
}
}
Similar Reads
Java Program to Extract Content from a Java's .class File In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract
2 min read
Java program to merge contents of all the files in a directory Prerequisite : PrintWriter, BufferedReader. We are given a directory/folder in which n number of files are stored(We dont know the number of files) and we want to merge the contents of all the files into a single file lets say output.txt For the below example lets say the folder is stored at the pat
2 min read
Java Program to Extract Content from a TXT document Java class< file using the Apache Tika library is used. Â For document type detection and content extraction from various file formats, it uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing different file fo
3 min read
Java Program to Create a New File There are two standard methods to create a new file, either directly with the help of the File class or indirectly with the help of the FileOutputStream class by creating an object of the file in both approaches.Methods to Create Files in JavaThere are two methods mentioned belowUsing the File Class
4 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 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 Extract Content from a HTML document HTML is the core of the web, all the pages you see on the internet are HTML, whether they are dynamically generated by JavaScript, JSP, PHP, ASP, or any other web technology. Your browser actually parses HTML and render it for you But if we need to parse an HTML document and find some elements, tags
4 min read
Convert String to Stream of Chars in Java The StringReader class from the java.io package in Java can be used to convert a String to a character stream. When you need to read characters from a string as though it were an input stream, the StringReader class can be helpful in creating a character stream from a string. In this article, we wil
2 min read
How to Extract File Extension From a File Path String in Java? In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Pr
5 min read
Java Program to Save a String to a File 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 wr
6 min read