How to get file content in java?
Asked Answered
S

6

44

to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))
Sainthood answered 12/4, 2011 at 20:16 Comment(0)
F
28

With Java 7 there is an API along those lines.

Files.readAllLines(Path path, Charset cs)

Fairground answered 12/4, 2011 at 20:18 Comment(3)
the link seems to be dead.Pulchi
Updated with fixed link.Fairground
cool, you could also use readAllBytes() and do the following one liner without any 3rd party library: String content = new String (Files.readAllBytes(new File("/my/file.txt")).toPath()))Halidom
S
36

Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
Strategist answered 12/4, 2011 at 20:17 Comment(1)
Files#toString is deprecated. Documentation states: Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be removed in January 2019.Lezley
F
28

With Java 7 there is an API along those lines.

Files.readAllLines(Path path, Charset cs)

Fairground answered 12/4, 2011 at 20:18 Comment(3)
the link seems to be dead.Pulchi
Updated with fixed link.Fairground
cool, you could also use readAllBytes() and do the following one liner without any 3rd party library: String content = new String (Files.readAllBytes(new File("/my/file.txt")).toPath()))Halidom
M
20

commons-io has:

IOUtils.toString(new FileReader("file.txt"), "utf-8");
Muumuu answered 12/4, 2011 at 20:21 Comment(0)
T
16
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = Files.readString(Paths.get("foo"));
}

From https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

Tureen answered 26/5, 2016 at 16:6 Comment(1)
Files.readString() in Java 11 makes it even simpler.Quadruplicate
B
7

You could use the FileReader class together with the BufferedReader to read the text file.

File fileToRead = new File("file.txt");

try( FileReader fileStream = new FileReader( fileToRead ); 
    BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {

    String line = null;

    while( (line = bufferedReader.readLine()) != null ) {
        //do something with line
    }

    } catch ( FileNotFoundException ex ) {
        //exception Handling
    } catch ( IOException ex ) {
        //exception Handling
}
Busra answered 27/10, 2016 at 12:4 Comment(0)
L
0

After a bit of testing, I find BufferedReader and Scanner both problematic under various circumstances (the former often fails to detect new lines and the latter often strips spaces, for instance, from a JSON string exported by org.json library). There are other methods available but the problem is they are only supported after certain Java versions (which is bad for an Android developer, for example) and you might not want to use Guava or Apache commons library just for a single purpose like this. Hence, my solution is to read the whole file as bytes and convert it to string. The code below are taken from one of my hobby projects:

    /**
     * Get byte array from an InputStream most efficiently.
     * Taken from sun.misc.IOUtils
     * @param is InputStream
     * @param length Length of the buffer, -1 to read the whole stream
     * @param readAll Whether to read the whole stream
     * @return Desired byte array
     * @throws IOException If maximum capacity exceeded.
     */
    public static byte[] readFully(InputStream is, int length, boolean readAll)
            throws IOException {
        byte[] output = {};
        if (length == -1) length = Integer.MAX_VALUE;
        int pos = 0;
        while (pos < length) {
            int bytesToRead;
            if (pos >= output.length) {
                bytesToRead = Math.min(length - pos, output.length + 1024);
                if (output.length < pos + bytesToRead) {
                    output = Arrays.copyOf(output, pos + bytesToRead);
                }
            } else {
                bytesToRead = output.length - pos;
            }
            int cc = is.read(output, pos, bytesToRead);
            if (cc < 0) {
                if (readAll && length != Integer.MAX_VALUE) {
                    throw new EOFException("Detect premature EOF");
                } else {
                    if (output.length != pos) {
                        output = Arrays.copyOf(output, pos);
                    }
                    break;
                }
            }
            pos += cc;
        }
        return output;
    }

    /**
     * Read the full content of a file.
     * @param file The file to be read
     * @param emptyValue Empty value if no content has found
     * @return File content as string
     */
    @NonNull
    public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
        if (file.isDirectory()) return emptyValue;
        try {
            return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
            return emptyValue;
        }
    }

You can simply use getFileContent(file, "") to read the content of a file.

Loni answered 7/8, 2020 at 7:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.