Algorithm


  1. Open File:

    • Open the file using a FileReader or BufferedReader.
  2. Read File Contents:

    • Create a StringBuilder or StringBuffer to store the contents of the file.
    • Use a loop to read the file line by line or character by character.
    • Append each line or character to the StringBuilder.
  3. Close File:

    • Close the file to free up system resources.
  4. Handle Exceptions:

    • Use try-catch blocks to handle any potential IOExceptions that may occur during file operations.
  5. Return Result:

    • Convert the StringBuilder content to a String.

 

Code Examples

#1 Code Example- Java Programing Create String from file

Code - Java Programming

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class FileString {

    public static void main(String[] args) throws IOException {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        Charset encoding = Charset.defaultCharset();

        List < String> lines = Files.readAllLines(Paths.get(path), encoding);
        System.out.println(lines);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
[This is a, Test file.]

#2 Code Example- Java Programing Create String from a file

Code - Java Programming

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

public class FileString {

    public static void main(String[] args) throws IOException {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        Charset encoding = Charset.defaultCharset();

        byte[] encoded = Files.readAllBytes(Paths.get(path));
        String lines = new String(encoded, encoding);
        System.out.println(lines);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
This is a Test file.
Advertisements

Demonstration


Java Programing Example to Create String from Contents of a File-DevsEnv