Java Files.readAllBytes example

In Java, we can use Files.readAllBytes to read a file.


	byte[] content = Files.readAllBytes(Paths.get("app.log"));
    System.out.println(new String(content));

1. Text File

A Java example to write and read a normal text file.

FileExample1.java

package com.mkyong.calculator;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class FileExample1 {

    public static void main(String[] args) {

        Charset utf8 = StandardCharsets.UTF_8;
        List<String> list = Arrays.asList("Line 1", "Line 2");
        
		// Write
        try {
            Files.write(Paths.get("app.log"), list, utf8, 
				StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }

        // Read
        try {
            byte[] content = Files.readAllBytes(Paths.get("app.log"));
            System.out.println(new String(content));

            // for binary
            //System.out.println(Arrays.toString(content));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

Output

app.log

Line 1
Line 2

2. Binary File

For binary format, we need to use Arrays.toString to convert it to a String.

FileExample2.java

package com.mkyong;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

public class FileExample2 {

    public static void main(String[] args) {

        byte[] bytes = {1, 2, 3, 4, 5};

		// Write into binary format
        try {
          
            Files.write(Paths.get("app.bin"), bytes, 
				StandardOpenOption.CREATE, StandardOpenOption.APPEND);

        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }

        // Read
        try {
            byte[] content = Files.readAllBytes(Paths.get("app.bin"));
            // for binary
            System.out.println(Arrays.toString(content));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

Output

app.bin

[1, 2, 3, 4, 5]

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar