Take the text from a flat file (File.txt) and save it in a string


As the title says I would like help to be able to take the text of "x" file and save it in a string to be able to traverse character by character.

thanks in advance

asked by Lorenzo Zuluaga 27.09.2016 в 22:08

2 answers


Read all the text in a file

Here I leave a compact routine for Java 7, wrapped in a utilitarian 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 in a file

Java 7 added a method to read a file as lines of text represented in a List<String> . This approach loses information since the line separators are removed from each of them.

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

Memory usage

The first method, which retains the line separators may temporarily require memory several times the size of the file, because, for a short period of time, the flat content of the file (an array of bytes), and the characters decoded (each occupying 16 bits even when the encoding is 8 bits in the file) reside in memory at the same time. It is safer to apply it to files that are known in advance that they are small in relation to the available memory.

The second method, which reads lines, is usually more efficient in memory usage, since the input buffer to decode does not contain the entire file. However, it is also not recommended for files that are very large relative to the available memory.

To read large files, you need to design the program differently. Read a piece of text from the stream, process it, and then move to the next piece, reusing a block of memory of constant size. Here, "large" depends on the specifications of the equipment. These days, this limit may be in the order of the Gibabytes of RAM.

Character encoding

There are special cases where the default of the platform is just what you want, but there are others where you need the power to choose.

The StandardCharsets class defines some constants for the encodings, required for all Java runtime.

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

The defualt of the platform is available at class Charset same:

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

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

answered by 27.09.2016 в 22:20

Java 7 +

Path path = Paths.get("directorio", "archivo.txt");
Charset charset = Charset.forName("UTF-8");
List<String> lines = Files.readAllLines(path, charset);
StringBuilder builder = new StringBuilder();

lines.forEach(line -> builder.append(line));
return builder.toString();
answered by 27.09.2016 в 22:18