×

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

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.