Java Read File to String
There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications.
There are different ways to deal with looking at a plain text record in Java for example you can utilize FileReader, BufferedReader or Scanner to examine a text report.
Given a message record, the undertaking is to peruse the items in a document present in a nearby registry and putting away it in a string.
Consider a record present on the framework to be specific say it be 'file.txt'.
Give the arbitrary substance access the record be as embedded underneath in the pretag block.
Presently we will talk about out different ways of accomplishing something similar. The substance inside document 'file.txt' is as displayed in the outline block.
Methods:
There are multiple ways of accomplishing the objective and with the progression of the form in java, explicit strategies are there spread out which are talked about successively.
- Using File.readString() strategy
- Using readLine() strategy for BufferReader class
- Using File.readAllBytes() strategy
- Using File.lines() strategy
- Using Scanner class
Using File.readString() strategy: The readString() technique for File Class in Java is utilized to peruse items to the predefined document.
Syntax:
Files.readString(filePath);
Boundaries: File way with information type as Path
Return Value: This technique returns the substance of the document in String design.
Note: File.readString() technique was presented in Java 11 and this strategy is utilized to peruse a document's substance into String.
//example to understand more about this
// Java Program Illustrating Reading a File to a String
// Utilizing File.readString() strategy
// Bringing in required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
// Principal class
public class RS1 {
// Principal driver strategy
public static void main(String[] args) throws IOException
{
// Making a way picking document from nearby
// catalog by making an object of Path class
Way filename = Path.of("C:\\Users\\VICTUS\\Desktop\\bhoomika.txt");
// Presently calling Files.readString() strategy to
// peruse the record
String str = Files.readString(fileName);
// Printing the string
System.out.println(str);
}
}
Using readLine() strategy for BufferReader class:
BufferedReader is an item used to peruse text from a person input stream. The readLine() strategy present in BufferReader technique is utilized to peruse the record each line in turn and return the substance.
Linguistic structure: public String readLine() throws IOException
Boundaries: This strategy acknowledges no boundary.
Return Value: This strategy returns the string that is perused by this technique and prohibits any end image accessible. Assuming the cradled stream has finished and there is no line to be perused then this technique brings NULL back.
Special cases: This technique tosses IOException if an I/O mistake happens.
//simple program
// Java Program Illustrating Reading a File to a String
// Using readLine() method of BufferReader class
// Importing required classes
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// Main class
public class RS2 {
// To read file content into the string
// using BufferedReader and FileReader
private static String method(String filePath)
{
// Declaring object of StringBuilder class
StringBuilder builder = new StringBuilder();
// try block to check for exceptions where
// object of BufferedReader class us created
// to read filepath
try (BufferedReaderbuffer = new BufferedReader(new FileReader(filePath))) {
String str;
// Condition check via buffer.readLine() method
// holding true upto that the while loop runs
while ((str = buffer.readLine()) != null) {
builder.append(str).append("\n");
}
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the line number here exception occurred
// using printStackTrace() method
e.printStackTrace();
}
// Returning a string
return builder.toString();
}
}
Using File.readAllBytes() strategy: File.readAllBytes() technique is utilized to peruse every one of the bytes from a document.
The system guarantees that the record is shut when all bytes have been analyzed or an I/O mess up, or other runtime exemption, is tossed.
Resulting to scrutinizing all bytes, we pass those bytes to the string class constructor to make a string.
Language structure:
public static byte[] ReadAllBytes (string way);
Boundary: Path which is the predetermined document to open for perusing.
Approach:
Proclaiming a vacant string
get() strategy for Path class helps in bringing the record by passing as a contention to it.
Presently readAllBytes() strategy for the File class is utilized to add the above record by passing to it.
Ultimately, print the string.
Exceptions:
- ArgumentException: The way is a zero-length string, contains just void area, or at least one invalid characters as characterized by InvalidPathChars.
- ArgumentNullException: The way is invalid.
- PathTooLongException: The predefined way, record name, or both surpass the framework characterized greatest length.
- DirectoryNotFoundException: The predetermined way is invalid.
- IOException: An I/O mistake happened while opening the record.
- UnauthorizedAccessException: This activity isn't upheld on the ongoing stage.Then again the way shown a list. Then again the visitor doesn't have the normal assent.
- FileNotFoundException: The record determined in the way was not found.
- NotSupportedException: The way is in an invalid organization.
- SecurityException: The guest doesn't have the necessary authorization
//simple program
// Java Program Illustrating Reading a File to a String
// Utilizing File.readAllBytes() strategy
// Bringing in required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// Primary class
public class RS3 {
// Strategy 1
// To peruse the document content into string with
// Files.readAllBytes(Path way)
confidential static String method(String file_path)
{
// Proclaiming an unfilled string
String str = "";
// Attempt block to check for special cases
try{
// Perusing all bytes structure record and
// putting away that in the string
str = new String(
Files.readAllBytes(Paths.get(file_path)));
}
// Get block to deal with the exemptions
get (IOException e) {
// Print the special case alongside line number
// utilizing printStackTrace() technique
e.printStackTrace();
}
return str;
}
// Strategy 2
// Principal driver strategy
public static void main(String[] args)
{
// Way is passed from nearby catalog of machine
// what's more, put away in a string
String filePath = "C:\\Users\\VICTUS\\Desktop\\file.txt";
// Presently call Method1 to
// peruse the substance in above registry
System.out.println(method(filePath));
}
}
Using File.lines() strategy: File.lines() strategy is utilized to peruse all lines from a document to stream. Then, at that point, the bytes from the record are decoded into characters utilizing the predetermined charset like UTF_8.
Language structure:
public static Stream<String> lines(Path way, Charset cs) throws IOException
Boundaries: It conventionally takes two boundaries:
Charset to use for unraveling.
Way of the record.
Return Type: The lines from the record as a string.
//simple program
// Java Program Illustrating Reading a File to a String
// Utilizing File.lines() strategy
// Bringing in required classes
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;
// Primary class
public class RS4 {
// Strategy 1
// To peruse the document content into the string with -
// Files.lines()
confidential static String method(String filePath)
{
// Pronouncing an object of StringBuilder class
StringBuilder contentBuilder = new StringBuilder();
// attempt block to check for special cases
// Perusing document to string utilizing File.lines() technique
// also, putting away it in an object of Stream class
attempt (Stream<String> stream
= Files.lines(Paths.get(filePath),
StandardCharsets.UTF_8)) {
stream.forEach(
s - > contentBuilder.append(s).append("\n"));
}
// Get block to deal with the special cases
get (IOException e) {
// Print the line number where exemption happened
// utilizing printStackTrace() strategy
e.printStackTrace();
}
// Returning the string manufacturer by
// calling tostring() strategy
return contentBuilder.toString();
}
// Strategy 2
// Principal driver technique
public static void main(String[] args)
{
// Custom record way is put away as string
String filePath = "C:\\Users\\HP\\VICTUS\\bhoomika.txt";
// Calling strategy 1 to peruse content of a record
System.out.println(method(filePath));
}
}
Using Scanner class: Scanner class works by breaking the contribution to tokens that are consecutively recovered from the information stream.
Scanner class has two in form strategies named straightaway() and hasNext(). Both of these in-form strategies return objects of type String.
//simple program
// Java Program Illustrating Reading a File to a String
// Utilizing straightaway() and hasNext() strategy for Scanner class
// Bringing in required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
// Principal class
public class RS5 {
// Principal driver strategy
public static void main(String[] args)
throws IOException
{
// Making object of Path class where custom neighborhood
// catalog way is passed as contentions utilizing .of()
// strategy
Way fileName
= Path.of("C:\\Users\\VICTUS\\Desktop\\bhoomika.txt");
// Making an object of Scanner class
Scanner sc = new Scanner(fileName);
// It turns out as expected till there is single component left
// by means of hasNext() strategy
while (sc.hasNext()) {
// Repeating over components in object
System.out.println(sc.next());
}
// Shutting scanner class object to keep away from mistakes and
// let loose memory space
sc.close();
}
}