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());
        }
    }

}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap