Java: Convert a Text file into Array of Bytes Example

We can make use of BufferedReader to read the file line by line, concatenate the lines into a single string using a StringBuilder, convert the string to an array of bytes using the getBytes() method with UTF-8 encoding, and print the length of the byte array.

Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("my_data.txt"))) {

            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
            String text = sb.toString();
            byte[] bytes = text.getBytes("UTF-8");
            System.out.println(bytes.length);
        } catch (IOException e) {
            System.out.println("Error while reading the file: " + e.getMessage());
        }
    }

}

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!