Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #58 Extract file content to a string

Create the string lines from the content of the file with filename f.

import java.nio.file.Files;
import java.nio.charset.StandardCharsets;
byte[] encoded = Files.readAllBytes(Paths.get(f));
String lines = new String(encoded, StandardCharsets.UTF_8);

You have to know and explicitly tell the charset used in the file.
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
import java.io.File;
import java.util.Scanner;
File F = new File(f);
try (Scanner s = new Scanner(F)) {
    s.useDelimiter("\\R");
    String n = lineSeparator(),
           lines = s.tokens()
                    .collect(joining(n));
}
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
FILE *file;
size_t len=0;
char *lines;
assert(file=fopen(f,"rb"));
assert(lines=malloc(sizeof(char)));

while(!feof(file))
{
	assert(lines=realloc(lines,(len+0x1000)*sizeof(char)));
	len+=fread(lines,1,0x1000,file);
}

assert(lines=realloc(lines,len*sizeof(char)));

New implementation...
< >
programming-idioms.org