How do I create a Java string from the contents of a file? convert file to Java String.


How do I create a Java string from the contents of a file? convert the file to Java String.

The following a possible way for getting data from the file as a String form.
Read all text from a file
First Solution:-
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

String content = new String(Files.readAllBytes(Paths.get("readMe.txt")), StandardCharsets.UTF_8);

Second Solution:-
Guava has a method similar to the one from Commons IOUtils that Williams Rohr mentioned:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
// ...
String text = Files.toString(new File(path), Charsets.UTF_8);

Third Solution:-
Java 11 added the readString() method to read small files as a String, preserving line terminators:
String content = Files.readString(path, StandardCharsets.US_ASCII);
For versions between Java 7 and 11, here's a compact, robust the idiom, wrapped up in a utility method:
static String readFile(String path, Charset encoding)
  throws IOException
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

4th Solution:-
A very lean solution based on Scanner:
Scanner scanner = new Scanner( new File("poem.txt") );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block
Or, if you want to set the charset:
Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

5th Solution:-
import java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;
 
public String readFile() throws IOException {
    File file = new File("data.txt");
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}

Comments

Popular posts from this blog

What is SIP or Session Initiation Protocol ?

How To Create An Object In Java ?

How do I declare and initialize an array in Java?