Logo

Programming-Idioms

  • JS
  • 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));
}
var fs = require('fs');
fs.readFile(f, (err, lines) => {
    if (err) {
        // Handle error...
    }

    // Work with `lines` here.
}

Uses Node-specific file-system API.
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int err = 0;
int fd = 0;
void * ptr = NULL;
struct stat st;
if ((fd = open (f, O_RDONLY))
&& (err = fstat (fd, &st)) == 0
&& (ptr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != -1) {
    const char * lines = ptr;
    puts (lines);
    munmap (ptr, st.st_size);
    close (fd);
}

Mapping the whole file into the process address space avoids allocating memory.

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