How to Create a Java String from the Contents of a File

How do I create a Java string from the contents of a file?

Read all text from a file

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 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);
}

Read lines of text from a file

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

Java 8 added the Files.lines() method to produce a Stream<String>. Again, this method is lossy because line separators are stripped. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

try (Stream<String> lines = Files.lines(path, encoding)) {
lines.forEach(System.out::println);
}

This Stream does need a close() call; this is poorly documented on the API, and I suspect many people don't even notice Stream has a close() method. Be sure to use an ARM-block as shown.

If you are working with a source other than a file, you can use the lines() method in BufferedReader instead.

Memory utilization

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream<String> is one way to do this, if your input "records" happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)

Character encoding

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

The StandardCharsets class defines some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset());

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

What is simplest way to read a file into String?

Yes, you can do this in one line (though for robust IOException handling you wouldn't want to).

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

There is a constructor that takes a File and a String charSetName (among many other overloads). These two constructor may throw FileNotFoundException, but like all Scanner methods, no IOException can be thrown beyond these constructors.

You can query the Scanner itself through the ioException() method if an IOException occurred or not. You may also want to explicitly close() the Scanner after you read the content, so perhaps storing the Scanner reference in a local variable is best.

See also

  • Java Tutorials - I/O Essentials - Scanning and formatting

Related questions

  • Validating input using java.util.Scanner - has many examples of more typical usage

Third-party library options

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

Guava

com.google.common.io.Files contains many useful methods. The pertinent ones here are:

  • String toString(File, Charset)

    • Using the given character set, reads all characters from a file into a String
  • List<String> readLines(File, Charset)

    • ... reads all of the lines from a file into a List<String>, one entry per line

Apache Commons/IO

org.apache.commons.io.IOUtils also offer similar functionality:

  • String toString(InputStream, String encoding)

    • Using the specified character encoding, gets the contents of an InputStream as a String
  • List readLines(InputStream, String encoding)

    • ... as a (raw) List of String, one entry per line

Related questions

  • Most useful free third party Java libraries (deleted)?

Save content of File as String in Java?

I hope this is what you need:

public void loadUserData(ArrayList<User> arraylist) {
StringBuilder sb = new StringBuilder();
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
// String[] userParams = line.split(";");

//String name = userParams[0];
//String number= userParams[1];
//String mail = userParams[2];
sb.append(line);
}
String jdbcString = sb.toString();
System.out.println("JDBC statements read from file: " + jdbcString );
} catch (IOException e) {
e.printStackTrace();
}
}

or maybe this:

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

Create a class that displays the content of the text file to console with some changes

public class Converter {

//helper enum
enum Language {
cyr,
lat,
none
}

// if you have to return more that two types of values then use enum
private static Language defineLocale(String string) {
char ch = string.charAt(0);

if (Character.isAlphabetic(ch)) {
if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.CYRILLIC)) {
return Language.cyr;
} else if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.BASIC_LATIN)){
return Language.lat;
}
}

return Language.none;
}


public void convert() {
try (BufferedReader in = new BufferedReader(new FileReader("part1.txt"))) {

String line;
StringBuilder result = new StringBuilder();

while ((line = in.readLine()) != null) {
String[] wordsInLine = line.split(" ");

for (String s : wordsInLine) {
if (s.length() > 3) {
switch (defineLocale(s)) {
case cyr:
result.append(s.substring(4));
break;
case lat:
result.append(s.substring(2));
break;
default:
result.append(s);
}
} else result.append(s);
result.append(" ");
}

result.append("\n");//all you were missing
}

System.out.println(result);
}catch(IOException e){
e.getMessage();
}
}
public static void main(String[] args){
new Converter().convert();
}
}

I hope this does not need any further explanation but dont be shy to ask if you dont understand something.

Whole text file to a String in Java

Java 11 adds support for this use-case with Files.readString, sample code:

Files.readString(Path.of("/your/directory/path/file.txt"));

Before Java 11, typical approach with standard libraries would be something like this:

public static String readStream(InputStream is) {
StringBuilder sb = new StringBuilder(512);
try {
Reader r = new InputStreamReader(is, "UTF-8");
int c = 0;
while ((c = r.read()) != -1) {
sb.append((char) c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}

Notes:

  • in order to read text from file, use FileInputStream
  • if performance is important and you are reading large files, it would be advisable to wrap the stream in BufferedInputStream
  • the stream should be closed by the caller

How to load a text file to a string variable in java

Although I'm not a Java expert, I'm pretty sure this is the information you're looking for It looks like this:

static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}

Basically all languages provide you with some methods to read from the file system you're in. Hope that does it for you!

Good luck with your project!

How do you create a string array list from a text file in java?

Here is alternative way how to accomplish your task:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Scan {

public static void main(String[] args) {
String fileName = "text.txt";
List<Name> names = new ArrayList<>();

try (Scanner scan = new Scanner(new File(fileName))) {
while (scan.hasNext())
names.add(new Name(scan.nextLine().replace(",", "")));

} catch (FileNotFoundException e) {
e.printStackTrace();
}

System.out.println(names);
}

public static class Name {
private final String studentName;

public Name(String studentName) {
this.studentName = studentName;
}

public String getstudentName() {
return studentName;
}

@Override
public String toString() {
return studentName;
}
}
}

By using class Scanner you can read a file as follow: Scanner scan = new Scanner(new File(fileName)). Read file line by line: scan.nextLine() until end of file: while (scan.hasNext()). Create new instance of Name: new Name(scan.nextLine().replace(",", "")) and add it into list: names.add(...). To remove , used replace(",", "") method of String class.



Related Topics



Leave a reply



Submit