Java Program to Read a File to String
Last Updated :
10 Oct, 2022
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 of a file present in a local directory and storing it in a string. Consider a file present on the system namely say it be ‘gfg.txt’. Let the random content in the file be as inserted below in the pretag block. Now we will be discussing out various ways to achieve the same. The content inside file ‘gfg.txt’ is as shown in the illustration block.
Illustration: Lines inside the file
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Note: Save above text file to your local computer with .txt extension and use that path in the programs.
Methods:
There are several ways to achieve the goal and with the advancement of the version in java, specific methods are there laid out which are discussed sequentially.
Methods:
- Using File.readString() method
- Using readLine() method of BufferReader class
- Using File.readAllBytes() method
- Using File.lines() method
- Using Scanner class
Let us discuss each of them by implementing clean java programs in order to understand them.
Method 1: Using File.readString() method
The readString() method of File Class in Java is used to read contents to the specified file.
Syntax:
Files.readString(filePath) ;
Parameters: File path with data type as Path
Return Value: This method returns the content of the file in String format.
Note: File.readString() method was introduced in Java 11 and this method is used to read a file’s content into String.
Example
Java
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class GFG {
public static void main(String[] args)
throws IOException
{
Path fileName
= Path.of( "C:\\Users\\HP\\Desktop\\gfg.txt" );
String str = Files.readString(fileName);
System.out.println(str);
}
}
|
Output:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Method 2: Using readLine() method of BufferReader class
BufferedReader is an object used to read text from a character-input stream. The readLine() method present in BufferReader method is used to read the file one line at a time and return the content.
Syntax:
public String readLine()
throws IOException
Parameters: This method does not accept any parameter.
Return value: This method returns the string that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL.
Exceptions: This method throws IOException if an I/O error occurs.
Example
Java
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class GFG {
private static String method(String filePath)
{
StringBuilder builder = new StringBuilder();
try (BufferedReader buffer = new BufferedReader(
new FileReader(filePath))) {
String str;
while ((str = buffer.readLine()) != null ) {
builder.append(str).append( "\n" );
}
}
catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
public static void main(String[] args)
{
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt" ;
System.out.println(method(filePath));
}
}
|
Output:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Method 3: Using File.readAllBytes() method
File.readAllBytes() method is used to read all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all bytes, we pass those bytes to the string class constructor to create a string.
Syntax:
public static byte[] ReadAllBytes (string path);
Parameter: Path which is the specified file to open for reading.
Approach:
- Declaring an empty string
- get() method of Path class helps in fetching the file by passing as an argument to it.
- Now readAllBytes() method of the File class is used to read the above file by passing into it.
- Lastly, print the string.
Exceptions:
- ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
- ArgumentNullException: The path is null.
- PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
- DirectoryNotFoundException: The specified path is invalid.
- IOException: An I/O error occurred while opening the file.
- UnauthorizedAccessException: This operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission.
- FileNotFoundException: The file specified in the path was not found.
- NotSupportedException: The path is in an invalid format.
- SecurityException: The caller does not have the required permission.
Example
Java
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class GFG {
private static String method(String file_path)
{
String str = "" ;
try {
str = new String(
Files.readAllBytes(Paths.get(file_path)));
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args)
{
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt" ;
System.out.println(method(filePath));
}
}
|
Output:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Method 4: Using File.lines() method
File.lines() method is used to read all lines from a file to stream. Then the bytes from the file are decoded into characters using the specified charset like UTF_8.
Syntax:
public static Stream<String> lines(Path path, Charset cs)
throws IOException
Parameters: It generically takes two parameters:
- Charset to use for decoding.
- Path of the file.
Return Type: The lines from the file as a string.
Example
Java
import java.io.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class GFG {
private static String method(String filePath)
{
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream
= Files.lines(Paths.get(filePath),
StandardCharsets.UTF_8)) {
stream.forEach(
s -> contentBuilder.append(s).append( "\n" ));
}
catch (IOException e) {
e.printStackTrace();
}
return contentBuilder.toString();
}
public static void main(String[] args)
{
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt" ;
System.out.println(method(filePath));
}
}
|
Output:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Method 5: Using next() and hasNext() method of Scanner class
Scanner class works by breaking the input into tokens that are sequentially retrieved from the input stream. Scanner class has two in build methods named next() and hasNext(). Both of these in-build methods return objects of type String.
Example
Java
import java.io.*;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
throws IOException
{
Path fileName
= Path.of( "C:\\Users\\HP\\Desktop\\gfg.txt" );
Scanner sc = new Scanner(fileName);
while (sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();
}
}
|
Output:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...