How do I read a file into byte array?

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ReadFileIntoByteArray {
    public static void main(String[] args) throws IOException {
        File file = new File("README.md");
        try (InputStream is = new FileInputStream(file)) {
            if (file.length() > Integer.MAX_VALUE) {
                throw new IOException("File is too large.");
            }

            int offset = 0;
            int bytesRead;
            byte[] bytes = new byte[(int) file.length()];
            while (offset < bytes.length
                    && (bytesRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += bytesRead;
            }
        }
    }
}

How do I get the content of an InputStream as a String?

We can use the code below to convert the content of an InputStream into a String. At first, we use FileInputStream create to a stream to a file that going to be read. IOUtils.toString(InputStream input, String encoding) method gets the content of the InputStream and returns a string representation of it.

package org.kodejava.commons.io;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamToString {
    public static void main(String[] args) throws Exception {
        // Create an input stream for reading data.txt file content.
        try (InputStream is = new FileInputStream("data.txt")) {
            // Get the content of an input stream as a string using UTF-8
            // as the character encoding.
            String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
            System.out.println(contents);
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I convert InputStream to String?

This example will show you how to convert an InputStream into String. In the code snippet below we read a data.txt file, could be from common directory or from inside a jar file.

package org.kodejava.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StreamToString {

    public static void main(String[] args) throws Exception {
        StreamToString demo = new StreamToString();

        // Get input stream of our data file. This file can be in
        // the root of your application folder or inside a jar file
        // if the program is packed as a jar.
        InputStream is = demo.getClass().getResourceAsStream("/student.csv");

        // Call the method to convert the stream to string
        System.out.println(demo.convertStreamToString(is));
    }

    private String convertStreamToString(InputStream stream) throws IOException {
        // To convert the InputStream to String we use the
        // Reader.read(char[] buffer) method. We iterate until the
        // Reader return -1 which means there's no more data to
        // read. We use the StringWriter class to produce the string.
        if (stream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try (stream) {
                Reader reader = new BufferedReader(new InputStreamReader(stream,
                        StandardCharsets.UTF_8));
                int length;
                while ((length = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, length);
                }
            }
            return writer.toString();
        }
        return "";
    }
}

How do I convert string into InputStream?

Here you will find how to convert string into java.io.InputStream object using java.io.ByteArrayInputStream class.

package org.kodejava.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StringToStream {
    public static void main(String[] args) {
        String text = "Converting String to InputStream Example";

        // Convert String to InputStream using ByteArrayInputStream
        // class. This class constructor takes the string byte array
        // which can be done by calling the getBytes() method.
        InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
    }
}

How do I read image file?

Here you see a code sample to read an image file. This code will work either the image file is located in a file folder or inside a jar file. You can use javax.imageio.ImageIO class to read the image file.

package org.kodejava.awt;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class ReadingImage {
    public static void main(String[] args) {
        ReadingImage demo = new ReadingImage();
        demo.getImage();
    }

    public void getImage() {
        try {
            InputStream is = getClass().getResourceAsStream("/kodejava.png");
            BufferedImage image = ImageIO.read(is);

            // Do something with the image.
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}