How to Create String from Contents of a File in Java Program

How to Create String from content of a file in java program

Java Strings

  • A Java object that represents a string of characters is called a string. Strings are frequently employed to store text data like names, addresses, words, etc. A String class that comes with Java offers methods for comparing and manipulating strings.
  • Strings can be compared for equality using the equals method. For example, “Hello”.equals(“Hello”) returns true. Note that the == operator compares the memory addresses of two objects, not their values. To compare the values of two strings, use the equals method.

To know more about Java Program to Create string From Contents of a file, read the complete article.

Steps to Create String from Contents of a File in Java Program

  • To create String from Contents of a file in java program, you can follow these steps:
    • Import the Required Libraries.
    • Create a File object to represent the file:
    • Read the contents of the file into a byte[]:
    • Convert the byte[] to a string using the desired encoding.
    • Use the contents string as needed in the rest of your program.

Let’s look at a Java Program to Create String from Contents of a file to perform certain operations.

Example 1: Java Program to Create String from Contents of a file. 

Run
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    try {
      File file = new File("path/to/file");
      byte[] encoded = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
      String contents = new String(encoded, StandardCharsets.UTF_8);
      System.out.println(contents);
    } catch (IOException e) {
      System.out.println("PrepInsta: " + e.getMessage());
    }
  }
}

Output

PrepInsta: /home/path/to/file
NOTE: Make sure to replace "path/to/file" with the actual file path on your system

Example 2 : Java Program to Create String from Contents of a file. 

Run

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader("path/to/file"));
      StringBuilder builder = new StringBuilder();
      String line = reader.readLine();
      while (line != null) {
        builder.append(line);
        builder.append(System.lineSeparator());
        line = reader.readLine();
      }
      String contents = builder.toString();
      System.out.println(contents);
      reader.close();
    } catch (IOException e) {
      System.out.println("An error occurred while reading the file: " + e.getMessage());
    }
  }
}

Output

An error occurred while reading the file: path/to/file (No such file or directory)
NOTE: Make sure to replace "path/to/file" with the actual file path on your system

Example 3: Java Program Create String from contents of a file 

Run

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    try {
      String contents = new String(Files.readAllBytes(Paths.get("path/to/file")));
      System.out.println(contents);
    } catch (IOException e) {
      System.out.println("Prepinsta Prime: " + e.getMessage());
    }
  }
}

Output

Prepinsta Prime: path/to/file
NOTE: Make sure to replace "path/to/file" with the actual file path on your system

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription