How do I read a file into byte array?

package org.kodejava.example.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("Hello.txt");
        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 connection 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. In the end we need to close the InputStream in a finally block.

package org.kodejava.example.commons.io;

import org.apache.commons.io.IOUtils;

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

public class InputStreamToString {
    public static void main(String[] args) throws Exception {
        // Create an input stream for reading data.txt file content.
        InputStream is = new FileInputStream(new File("data.txt"));

        // Get the content of an input stream as a string using UTF-8
        // as the character encoding.
        try {
            String contents = IOUtils.toString(is, "UTF-8");
            System.out.println(contents);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

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.example.io;

import java.io.*;

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 you application folder or inside a jar file
        // if the program is packed as a jar.
        InputStream is = demo.getClass().getResourceAsStream("/data.txt");

        // 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 {
                Reader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                stream.close();
            }
            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.example.io;

import java.io.*;

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.
        try {
            InputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

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