×

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:

  1. ArgumentException: The way is a zero-length string, contains just void area, or at least one invalid characters as characterized by InvalidPathChars.
  2. ArgumentNullException: The way is invalid.
  3. PathTooLongException: The predefined way, record name, or both surpass the framework characterized greatest length.
  4. DirectoryNotFoundException: The predetermined way is invalid.
  5. IOException: An I/O mistake happened while opening the record.
  6. 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.
  7. FileNotFoundException: The record determined in the way was not found.
  8. NotSupportedException: The way is in an invalid organization.
  9. 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();
    }
}

Related Topics

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.